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

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 { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { servicesStore } from "@/lib/store/services-store";
import { categoryLabel } from "@/lib/mock/services";
import type { Service, ServiceCategory } from "@/lib/mock/types";

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

const CATEGORIES: ServiceCategory[] = [
  "sites",
  "landing",
  "ecommerce",
  "manutencao",
  "hospedagem",
  "email",
  "pacotes",
];

const emptyForm = {
  name: "",
  shortDescription: "",
  longDescription: "",
  basePrice: "",
  category: "sites" as ServiceCategory,
  active: true,
};

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

  useEffect(() => {
    if (!open) return;
    if (service) {
      setForm({
        name: service.name,
        shortDescription: service.shortDescription,
        longDescription: service.deliverables.join("\n"),
        basePrice: service.basePrice ? String(service.basePrice) : "",
        category: service.category,
        active: service.active,
      });
    } else {
      setForm(emptyForm);
    }
  }, [open, service]);

  const handleSave = () => {
    const name = form.name.trim();
    if (!name) {
      toast.error("Informe o nome do serviço");
      return;
    }
    if (name.length > 120) {
      toast.error("Nome muito longo (máx. 120 caracteres)");
      return;
    }

    const basePrice = form.basePrice
      ? Number(form.basePrice.replace(",", "."))
      : 0;
    if (form.basePrice && (Number.isNaN(basePrice) || basePrice < 0)) {
      toast.error("Valor base inválido");
      return;
    }

    const deliverables = form.longDescription
      .split("\n")
      .map((l) => l.trim())
      .filter(Boolean)
      .slice(0, 20);

    if (isEdit && service) {
      servicesStore.update(service.id, {
        name,
        shortDescription: form.shortDescription.trim().slice(0, 280),
        deliverables: deliverables.length ? deliverables : service.deliverables,
        basePrice,
        category: form.category,
        active: form.active,
      });
      toast.success("Serviço atualizado");
    } else {
      const newService: Service = {
        id: `svc-${Date.now()}`,
        name,
        shortDescription: form.shortDescription.trim().slice(0, 280),
        deliverables: deliverables.length ? deliverables : ["A definir"],
        basePrice,
        category: form.category,
        recurring: null,
        defaultDeadlineDays: 15,
        active: form.active,
      };
      servicesStore.add(newService);
      toast.success("Serviço criado");
    }
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="font-display">
            {isEdit ? "Editar serviço" : "Novo serviço"}
          </DialogTitle>
          <DialogDescription>
            {isEdit
              ? "Atualize as informações deste serviço."
              : "Cadastre um novo serviço no catálogo da X3 Sites."}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-4 py-2">
          <div className="grid gap-1.5">
            <Label htmlFor="svc-name">Nome do serviço *</Label>
            <Input
              id="svc-name"
              value={form.name}
              maxLength={120}
              onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              placeholder="Ex.: Criação de Landing Page"
            />
          </div>

          <div className="grid gap-1.5">
            <Label htmlFor="svc-short">Descrição curta</Label>
            <Input
              id="svc-short"
              value={form.shortDescription}
              maxLength={280}
              onChange={(e) =>
                setForm((f) => ({ ...f, shortDescription: e.target.value }))
              }
              placeholder="Resumo em uma linha"
            />
          </div>

          <div className="grid gap-1.5">
            <Label htmlFor="svc-long">Descrição completa / entregas</Label>
            <Textarea
              id="svc-long"
              value={form.longDescription}
              onChange={(e) =>
                setForm((f) => ({ ...f, longDescription: e.target.value }))
              }
              placeholder="Uma entrega por linha"
              rows={4}
            />
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="grid gap-1.5">
              <Label htmlFor="svc-price">Valor base (R$)</Label>
              <Input
                id="svc-price"
                inputMode="decimal"
                value={form.basePrice}
                onChange={(e) =>
                  setForm((f) => ({ ...f, basePrice: e.target.value }))
                }
                placeholder="0,00"
              />
            </div>
            <div className="grid gap-1.5">
              <Label>Categoria</Label>
              <Select
                value={form.category}
                onValueChange={(v) =>
                  setForm((f) => ({ ...f, category: v as ServiceCategory }))
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {CATEGORIES.map((c) => (
                    <SelectItem key={c} value={c}>
                      {categoryLabel[c]}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex items-center justify-between rounded-lg border border-border/60 p-3">
            <div>
              <Label htmlFor="svc-active" className="cursor-pointer">
                Serviço ativo
              </Label>
              <p className="text-xs text-muted-foreground">
                Serviços inativos não aparecem no wizard de propostas.
              </p>
            </div>
            <Switch
              id="svc-active"
              checked={form.active}
              onCheckedChange={(v) => setForm((f) => ({ ...f, active: v }))}
            />
          </div>
        </div>

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