'use client';

import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';

export default function ReferralPage() {
  const [form, setForm] = useState({
    yourName: '',
    yourMobile: '',
    yourEmail: '',
    product: '',
    friendName: '',
    friendMobile: '',
    preferredTime: '',
  });

  const [submitting, setSubmitting] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    try {
      const res = await fetch('/api/referral', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });

      const data = await res.json();
      if (data.success) {
        alert('Referral submitted!');
        setForm({
          yourName: '',
          yourMobile: '',
          yourEmail: '',
          product: '',
          friendName: '',
          friendMobile: '',
          preferredTime: '',
        });
      } else {
        alert('Submission failed.');
      }
    } catch (err) {
      console.error(err);
      alert('Error submitting referral.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-2xl mx-auto mt-10 p-6">
      <Card>
        <CardContent className="space-y-4">
          <h2 className="text-xl font-semibold text-blue-600">Referral Portal</h2>
          <p className="text-sm text-gray-500">Submit your details and your friend's info below.</p>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input name="yourName" placeholder="Your Name" value={form.yourName} onChange={handleChange} />
            <Input name="yourMobile" placeholder="Mobile No." value={form.yourMobile} onChange={handleChange} />
            <Input name="yourEmail" placeholder="Email ID" value={form.yourEmail} onChange={handleChange} />
            <Input name="product" placeholder="Product" value={form.product} onChange={handleChange} />
            <Input name="friendMobile" placeholder="Friend's Mobile No." value={form.friendMobile} onChange={handleChange} />
            <Input name="preferredTime" placeholder="Preferred Time to Call" value={form.preferredTime} onChange={handleChange} />
            <Input name="friendName" placeholder="Friend's Name" value={form.friendName} onChange={handleChange} />
          </div>

          <Button onClick={handleSubmit} disabled={submitting}>
            {submitting ? 'Submitting...' : 'Submit'}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
