"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { assignQuoteToLead } from "@/app/admin/leads/actions";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";

const assignQuoteSchema = z.object({
  lead_id: z.string(),
  quote_token: z.string().optional(),
});

export function SendQuoteModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  const form = useForm<any>({
    resolver: zodResolver(assignQuoteSchema),
    defaultValues: {
      lead_id: leadId,
      quote_token: "",
    },
  });

  async function onSubmit(data: any) {
    setLoading(true);
    try {
      const result = await assignQuoteToLead({
        lead_id: leadId,
        quote_token: data.quote_token,
      });
      if (result.success) {
        setOpen(false);
        form.reset();
      } else {
        console.error("Error assigning quote:", result.error);
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          Invia Preventivo
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Invia Preventivo al Lead</DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="quote_token"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Token Preventivo</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Incolla il token del preventivo"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <p className="text-xs text-gray-600">
              Copia il token dal preventivo e incollalo qui. Il lead sarà aggiornato a
              &quot;Proposal Sent&quot;.
            </p>
            <Button type="submit" disabled={loading} className="w-full">
              {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Invia
            </Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
