"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { addTranscript } from "@/app/admin/pipeline/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 { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Mic } from "lucide-react";

const transcriptSchema = z.object({
  lead_id: z.string().min(1),
  title: z.string().optional(),
  content: z.string().min(1, "Il testo del transcript è obbligatorio"),
  call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida"),
});

type TranscriptInput = z.infer<typeof transcriptSchema>;

export function TranscriptModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const form = useForm<TranscriptInput>({
    resolver: zodResolver(transcriptSchema),
    defaultValues: {
      lead_id: leadId,
      title: "",
      content: "",
      call_date: new Date().toISOString().split("T")[0],
    },
  });

  async function onSubmit(data: TranscriptInput) {
    setLoading(true);
    setError(null);
    try {
      const result = await addTranscript(data);
      if (result.success) {
        setOpen(false);
        form.reset({
          lead_id: leadId,
          title: "",
          content: "",
          call_date: new Date().toISOString().split("T")[0],
        });
      } else {
        setError(result.error ?? "Errore nel salvataggio");
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <button
          type="button"
          className="inline-flex items-center gap-2 px-4 py-2.5 border border-border text-muted-foreground hover:text-foreground hover:bg-muted text-xs font-semibold rounded-lg transition-colors"
        >
          <Mic className="w-4 h-4 text-muted-foreground/70" />
          Aggiungi Transcript
        </button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Aggiungi Transcript Call</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="call_date"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Data call</FormLabel>
                    <FormControl>
                      <Input type="date" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Titolo (opzionale)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="es. Discovery call"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="content"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Transcript</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Incolla qui il testo del transcript..."
                      className="min-h-48 resize-y"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {error && <p className="text-sm text-red-600">{error}</p>}

            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Salvataggio..." : "Salva Transcript"}
            </Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
