import { useEffect, useState } from "react";
import { toast } from "sonner";
import { z } from "zod";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { clientsStore, type ClientRecord } from "@/lib/store/clients-store";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  client?: ClientRecord | null;
};

const schema = z.object({
  name: z
    .string()
    .trim()
    .min(1, "Informe o nome do cliente")
    .max(160, "Nome muito longo"),
  contactName: z.string().trim().max(120).optional().or(z.literal("")),
  email: z
    .string()
    .trim()
    .min(1, "Informe o e-mail")
    .email("E-mail inválido")
    .max(255),
  phone: z.string().trim().max(40).optional().or(z.literal("")),
  website: z.string().trim().max(255).optional().or(z.literal("")),
  notes: z.string().trim().max(1000).optional().or(z.literal("")),
});

const emptyForm = {
  name: "",
  contactName: "",
  email: "",
  phone: "",
  website: "",
  notes: "",
};

export function ClientFormDialog({ open, onOpenChange, client }: Props) {
  const isEdit = Boolean(client);
  const [form, setForm] = useState(emptyForm);

  useEffect(() => {
    if (!open) return;
    if (client) {
      setForm({
        name: client.name,
        contactName: client.contactName ?? "",
        email: client.email ?? "",
        phone: client.phone ?? "",
        website: client.website ?? "",
        notes: client.notes ?? "",
      });
    } else {
      setForm(emptyForm);
    }
  }, [open, client]);

  const handleSave = () => {
    const parsed = schema.safeParse(form);
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? "Dados inválidos");
      return;
    }
    const data = parsed.data;

    if (isEdit && client) {
      clientsStore.update(client.id, {
        name: data.name,
        contactName: data.contactName || undefined,
        email: data.email,
        phone: data.phone || undefined,
        website: data.website || undefined,
        notes: data.notes || undefined,
      });
      toast.success("Cliente atualizado");
    } else {
      const newClient: ClientRecord = {
        id: `cli-${Date.now()}`,
        name: data.name,
        contactName: data.contactName || undefined,
        email: data.email,
        phone: data.phone || undefined,
        website: data.website || undefined,
        notes: data.notes || undefined,
      };
      clientsStore.add(newClient);
      toast.success("Cliente cadastrado");
    }
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="font-display">
            {isEdit ? "Editar cliente" : "Adicionar cliente"}
          </DialogTitle>
          <DialogDescription>
            {isEdit
              ? "Atualize as informações deste cliente."
              : "Cadastre um novo cliente para usar em suas propostas."}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-2">
          <div className="grid gap-1.5">
            <Label htmlFor="cli-name">Nome da empresa / cliente *</Label>
            <Input
              id="cli-name"
              value={form.name}
              maxLength={160}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              placeholder="Ex.: Padaria Pão Dourado"
            />
          </div>

          <div className="grid gap-1.5">
            <Label htmlFor="cli-contact">Nome do responsável</Label>
            <Input
              id="cli-contact"
              value={form.contactName}
              maxLength={120}
              onChange={(e) =>
                setForm((f) => ({ ...f, contactName: e.target.value }))
              }
              placeholder="Ex.: João Silva"
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="grid gap-1.5">
              <Label htmlFor="cli-email">E-mail *</Label>
              <Input
                id="cli-email"
                type="email"
                value={form.email}
                maxLength={255}
                onChange={(e) =>
                  setForm((f) => ({ ...f, email: e.target.value }))
                }
                placeholder="contato@empresa.com.br"
              />
            </div>
            <div className="grid gap-1.5">
              <Label htmlFor="cli-phone">WhatsApp</Label>
              <Input
                id="cli-phone"
                value={form.phone}
                maxLength={40}
                onChange={(e) =>
                  setForm((f) => ({ ...f, phone: e.target.value }))
                }
                placeholder="(55) 99999-9999"
              />
            </div>
          </div>

          <div className="grid gap-1.5">
            <Label htmlFor="cli-site">Site atual</Label>
            <Input
              id="cli-site"
              value={form.website}
              maxLength={255}
              onChange={(e) =>
                setForm((f) => ({ ...f, website: e.target.value }))
              }
              placeholder="https://..."
            />
          </div>

          <div className="grid gap-1.5">
            <Label htmlFor="cli-notes">Observações</Label>
            <Textarea
              id="cli-notes"
              value={form.notes}
              maxLength={1000}
              onChange={(e) =>
                setForm((f) => ({ ...f, notes: e.target.value }))
              }
              rows={3}
              placeholder="Notas internas sobre o cliente"
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancelar
          </Button>
          <Button onClick={handleSave} className="bg-gradient-brand text-white">
            {isEdit ? "Salvar alterações" : "Adicionar cliente"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
