import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2, Sparkles } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import type { Tour } from "@/types";

// Form validation schema
const leadFormSchema = z.object({
  email: z.string().email("Geçerli bir e-posta adresi giriniz"),
  whatsapp: z.string().min(10, "Geçerli bir WhatsApp numarası giriniz"),
  country: z.string().min(2, "Ülke bilgisi giriniz"),
  consent: z.boolean().refine((val) => val === true, {
    message: "Devam etmek için onay vermelisiniz",
  }),
});

type LeadFormValues = z.infer<typeof leadFormSchema>;

interface LeadCaptureModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedTour: Tour | null;
  tripData: {
    trip_id: string;
    destination: string;
    start_date: string;
    end_date: string;
    number_of_travelers: number;
    interests: string[];
    planned_activities: any;
    timeline_snapshot: any;
  };
  onSubmit: (contactInfo: {
    email: string;
    whatsapp: string;
    country: string;
    consent_given: boolean;
  }) => Promise<void>;
}

export function LeadCaptureModal({
  open,
  onOpenChange,
  selectedTour,
  tripData,
  onSubmit,
}: LeadCaptureModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);

  const form = useForm<LeadFormValues>({
    resolver: zodResolver(leadFormSchema),
    defaultValues: {
      email: "",
      whatsapp: "",
      country: "Türkiye",
      consent: false,
    },
  });

  const handleSubmit = async (values: LeadFormValues) => {
    setIsSubmitting(true);
    try {
      await onSubmit({
        email: values.email,
        whatsapp: values.whatsapp,
        country: values.country,
        consent_given: values.consent,
      });
      form.reset();
      onOpenChange(false);
    } catch (error) {
      console.error("Lead oluşturma hatası:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary" />
            Teklif Talebi
          </DialogTitle>
          <DialogDescription>
            {selectedTour?.name} için teklif almak üzeresiniz. İletişim bilgilerinizi paylaşın, size en kısa sürede dönüş yapalım.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>E-posta Adresi</FormLabel>
                  <FormControl>
                    <Input
                      type="email"
                      placeholder="ornek@email.com"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="whatsapp"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>WhatsApp Numarası</FormLabel>
                  <FormControl>
                    <Input
                      type="tel"
                      placeholder="+90 555 123 4567"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="country"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Ülke</FormLabel>
                  <FormControl>
                    <Input
                      type="text"
                      placeholder="Türkiye"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="consent"
              render={({ field }) => (
                <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border border-border p-4">
                  <FormControl>
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                  <div className="space-y-1 leading-none">
                    <FormLabel className="text-sm font-normal">
                      İletişim bilgilerimin tur sağlayıcıları ile paylaşılmasını ve teklif almak için iletişime geçilmesini kabul ediyorum.
                    </FormLabel>
                    <FormMessage />
                  </div>
                </FormItem>
              )}
            />

            <div className="flex gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => onOpenChange(false)}
                disabled={isSubmitting}
                className="flex-1"
              >
                İptal
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting}
                className="flex-1"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Gönderiliyor...
                  </>
                ) : (
                  "Teklif Talep Et"
                )}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
