"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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2 } from "lucide-react";

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

export function SendQuoteModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState<"existing" | "new">("existing");

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

  async function onSubmit(data: any) {
    setLoading(true);
    try {
      if (tab === "new") {
        // Redirect to quote builder pre-filled with this lead
        window.location.href = `/admin/quotes/new?lead_id=${leadId}`;
        return;
      }

      const result = await assignQuoteToLead({
        lead_id: leadId,
        quote_token: data.quote_token,
        generate_new: false,
      });
      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>
        <Tabs value={tab} onValueChange={(v) => setTab(v as "existing" | "new")}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="existing">Preventivo Esistente</TabsTrigger>
            <TabsTrigger value="new">Crea Nuovo</TabsTrigger>
          </TabsList>

          <TabsContent value="existing" className="mt-4">
            <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
                  "Proposal Sent".
                </p>
                <Button type="submit" disabled={loading} className="w-full">
                  {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Invia
                </Button>
              </form>
            </Form>
          </TabsContent>

          <TabsContent value="new" className="mt-4">
            <p className="text-sm text-gray-600 mb-4">
              Crea un nuovo preventivo per questo lead. Ti reindirizzeremo al builder.
            </p>
            <Button
              className="w-full"
              onClick={() => {
                window.location.href = `/admin/quotes/new?lead_id=${leadId}`;
              }}
            >
              Apri Quote Builder
            </Button>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
