import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { CalendarCheck, Link as LinkIcon } from 'lucide-react';

const SERVICE_OPTIONS = [
  { value: 'foreclosure-prevention', label: 'Foreclosure Prevention' },
  { value: 'fast-cash-offer', label: 'Fast Cash Offer' },
  { value: 'mortgage-reinstatement', label: 'Mortgage Reinstatement' },
  { value: 'general-consultation', label: 'General Real Estate Consultation' },
];

const MAX_LEAD_DAYS = 14;
const GOOGLE_APPOINTMENT_URL = import.meta.env.VITE_GOOGLE_APPOINTMENT_URL ?? '';

export interface AppointmentIntake {
  name: string;
  email: string;
  phone: string;
  propertyAddress: string;
  situation: string;
  serviceType: string;
}

export interface Appointment extends AppointmentIntake {
  id?: string;
  date?: string;
  time?: string;
  status?: 'pending' | 'confirmed' | 'completed' | 'cancelled';
  createdAt?: string;
  notes?: string;
}

export function AppointmentScheduler() {
  const [formData, setFormData] = useState<AppointmentIntake>({
    name: '',
    email: '',
    phone: '',
    propertyAddress: '',
    situation: '',
    serviceType: SERVICE_OPTIONS[0].value,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isComplete, setIsComplete] = useState(false);

  const handleChange = (field: keyof AppointmentIntake, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const launchGoogleSchedule = () => {
    if (!GOOGLE_APPOINTMENT_URL) {
      toast.error('Scheduling link is currently unavailable. Please call (615) 610-9857 to book.');
      return;
    }

    window.open(GOOGLE_APPOINTMENT_URL, '_blank', 'noopener,noreferrer');
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!formData.name || !formData.email || !formData.phone || !formData.propertyAddress || !formData.situation) {
      toast.error('Please fill in every field so we can prepare for your consultation.');
      return;
    }

    setIsSubmitting(true);

    try {
      // Persist intake details locally so the team can follow-up if needed.
      const existing = JSON.parse(localStorage.getItem('intake-requests') ?? '[]') as AppointmentIntake[];
      localStorage.setItem('intake-requests', JSON.stringify([...existing, formData]));

      toast.success('Thanks! Choose a time on the next screen to finish booking.');
      setIsComplete(true);
      launchGoogleSchedule();
    } catch (error) {
      console.error('Unable to store intake locally', error);
      toast.error('Something went wrong saving your details. Please try again or call us directly.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Card className="border-border">
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-xl">
          <CalendarCheck className="h-5 w-5 text-primary" />
          Book Your Consultation
        </CardTitle>
        <CardDescription>
          Secure a time in under a minute. Google Calendar keeps the next {MAX_LEAD_DAYS} days open,
          sends confirmations automatically, and reminds you before the call.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {!isComplete ? (
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="name">Full Name</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(event) => handleChange('name', event.target.value)}
                  placeholder="Your full name"
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="phone">Phone</Label>
                <Input
                  id="phone"
                  type="tel"
                  value={formData.phone}
                  onChange={(event) => handleChange('phone', event.target.value)}
                  placeholder="(615) 555-0123"
                  required
                />
              </div>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(event) => handleChange('email', event.target.value)}
                  placeholder="you@email.com"
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="serviceType">Service</Label>
                <Select
                  value={formData.serviceType}
                  onValueChange={(value) => handleChange('serviceType', value)}
                >
                  <SelectTrigger id="serviceType">
                    <SelectValue placeholder="Choose the support you need" />
                  </SelectTrigger>
                  <SelectContent>
                    {SERVICE_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="propertyAddress">Property Address</Label>
              <Input
                id="propertyAddress"
                value={formData.propertyAddress}
                onChange={(event) => handleChange('propertyAddress', event.target.value)}
                placeholder="123 Main St, Nashville, TN 37212"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="situation">Brief Situation Description</Label>
              <Textarea
                id="situation"
                value={formData.situation}
                onChange={(event) => handleChange('situation', event.target.value)}
                placeholder="Tell us what’s happening so we can prepare the right options for our call."
                minLength={20}
                rows={4}
                required
              />
            </div>

            <div className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
              Appointments are available within the next {MAX_LEAD_DAYS} days. Google automatically sends confirmation and reminder emails once you pick your time.
            </div>

            <Button
              type="submit"
              className="w-full"
              disabled={isSubmitting}
            >
              {isSubmitting ? 'Preparing your booking…' : 'Continue to Google Calendar'}
            </Button>
          </form>
        ) : (
          <div className="space-y-4 text-center">
            <p className="text-sm text-muted-foreground">
              Your details are saved. Finish your booking on Google Calendar to lock in a time within the next {MAX_LEAD_DAYS} days and receive automated reminders.
            </p>
            <div className="flex justify-center">
              <Button onClick={launchGoogleSchedule} className="gap-2">
                <LinkIcon className="h-4 w-4" />
                Open Google Calendar Scheduling
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">
              Need help right away? Call the 24/7 line at (615) 610-9857 after you book.
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

