import "@fontsource/playfair-display/400.css";
import "@fontsource/playfair-display/700.css";
import "@fontsource/playfair-display/400-italic.css";
import "@fontsource/inter/400.css";
import "@fontsource/inter/600.css";
import "@fontsource/inter/700.css";
import { useEffect, useMemo, useRef, useState } from "react";
import {
  ArrowLeft,
  Zap,
  Building2,
  Check,
  Clock,
  Contact,
  Copy,
  FileDown,
  Info,
  ListChecks,
  MessageCircle,
  Pencil,
  Pipette,
  Plus,
  PlusCircle,
  Receipt,
  RotateCcw,
  Save,
  Search,
  Smartphone,
  Trash2,

} from "lucide-react";
import {
  X,
  ChevronDown,
  ShieldCheck,
  CalendarClock,
  BadgeCheck,
  StickyNote,
  Package,
  Settings,
  FileText,
} from "lucide-react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";
import { useLocalStorage, formatBRL } from "@/features/orcamento/storage";
import { DEFAULT_SERVICES } from "@/features/orcamento/defaults";
import { DEFAULT_MATERIALS } from "@/features/orcamento/materialDefaults";
import { DEFAULT_CLAUSES } from "@/features/orcamento/clauseDefaults";
import {
  Budget,
  BudgetItem,
  ClientInfo,
  CompanyInfo,
  Service,
  Material,
  ExecutionInfo,
  DocumentKind,
} from "@/features/orcamento/types";

// Exporting formatting functions for use in other components
export { formatPhoneBR, formatDocumentBR };
import {
  type PdfFormat,
  type PdfResult,
} from "@/features/orcamento/exporters";
import PdfPreviewModal from "@/features/orcamento/PdfPreviewModal";
import { extractBrandColors } from "@/features/orcamento/extractBrandColors";
import { Onboarding } from "@/features/orcamento/Onboarding";
import { LogoEyedropper } from "@/features/orcamento/LogoEyedropper";

const uid = () =>
  typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : Math.random().toString(36).slice(2);

const emptyClient: ClientInfo = { name: "", phone: "", address: "", documentType: 'CPF' };

const emptyExecution: ExecutionInfo = {
  validityDays: 10,
  estimatedDeadline: "",
  estimatedDuration: "",
};

// Formata telefone brasileiro: (11) 91234-5678 ou (11) 1234-5678
const formatPhoneBR = (raw: string) => {
  const d = raw.replace(/\D/g, "").slice(0, 11);
  if (d.length === 0) return "";
  if (d.length <= 2) return `(${d}`;
  if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  if (d.length <= 10)
    return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
};

const formatDocumentBR = (raw: string, type?: "CPF" | "CNPJ") => {
  const d = raw.replace(/\D/g, "");
  const isCNPJ = type === "CNPJ" || (!type && d.length > 11);
  const digits = d.slice(0, isCNPJ ? 14 : 11);

  if (!isCNPJ) {
    // CPF: 000.000.000-00
    return digits
      .replace(/(\d{3})(\d)/, "$1.$2")
      .replace(/(\d{3})(\d)/, "$1.$2")
      .replace(/(\d{3})(\d{1,2})$/, "$1-$2");
  }
  // CNPJ: 00.000.000/0000-00
  return digits
    .replace(/(\d{2})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d)/, "$1/$2")
    .replace(/(\d{4})(\d{1,2})$/, "$1-$2");
};

// Switch deslizante com bom contraste em ambos os estados
const ToggleSwitch = ({
  checked,
  onChange,
  label,
}: {
  checked: boolean;
  onChange: () => void;
  label: string;
}) => (
  <button
    type="button"
    role="switch"
    aria-checked={checked}
    aria-label={label}
    onClick={(e) => {
      e.preventDefault();
      onChange();
    }}
    className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background ${
      checked ? "bg-primary" : "bg-muted border border-border"
    }`}
  >
    <span
      aria-hidden="true"
      className={`inline-block h-5 w-5 rounded-full bg-white shadow ring-1 ring-black/10 transition-transform duration-200 ${
        checked ? "translate-x-[22px]" : "translate-x-0.5"
      }`}
    />
  </button>
);

const App = () => {
  const [services, setServices] = useLocalStorage<Service[]>(
    "elg.services.v1",
    DEFAULT_SERVICES,
  );
  const [catalogMaterials, setCatalogMaterials] = useLocalStorage<Material[]>(
    "elg.catalogMaterials.v1",
    DEFAULT_MATERIALS,
  );
  const [company, setCompany] = useLocalStorage<CompanyInfo>("elg.company.v1", {
    name: "",
    document: "",
    documentType: "CPF",
    phone: "",
    email: "",
    city: "",
    state: "",
    pixKey: "",
    warrantyEnabled: true,
    warrantyDays: 90,
    validityEnabled: true,
    validityDays: 7,
    inmetroEnabled: true,
    customNote: "",
  });
  const [budgetNumber, setBudgetNumber] = useState<number | null>(null);
  const [client, setClient] = useLocalStorage<ClientInfo>(
    "elg.currentClient.v1",
    emptyClient,
  );
  const [items, setItems] = useLocalStorage<BudgetItem[]>(
    "elg.currentItems.v1",
    [],
  );
  const kind = "contrato";

  const [observations, setObservations] = useLocalStorage<string>("elg.observations.v1", "");
  const [materialProvidedByClient, setMaterialProvidedByClient] = useLocalStorage<boolean>("elg.materialProvidedByClient.v1", false);
  const [execution, setExecution] = useLocalStorage<ExecutionInfo>("elg.execution.v1", emptyExecution);
  const [paymentConditions, setPaymentConditions] = useLocalStorage<string>("elg.paymentConditions.v1", "");
  const [clauses, setClauses] = useLocalStorage<any[]>("elg.clauses.v1", DEFAULT_CLAUSES);
  const [startDate, setStartDate] = useLocalStorage<string>("elg.startDate.v1", "");
  const [endDate, setEndDate] = useLocalStorage<string>("elg.endDate.v1", "");
  const [cityOverride, setCityOverride] = useLocalStorage<string>("elg.cityOverride.v1", "");


  const initialCounter = useMemo(() => {
    if (typeof window === "undefined") return 1247;
    const stored = window.localStorage.getItem("elg.counter.v2");
    if (stored) return parseInt(stored, 10) || 1247;
    return 1200 + Math.floor(Math.random() * 3600);
  }, []);
  const [counter, setCounter] = useLocalStorage<number>("elg.counter.v2", initialCounter);
  const [laborCost, setLaborCost] = useLocalStorage<number>(
    "elg.currentLabor.v1",
    0,
  );
  const [materialCost, setMaterialCost] = useLocalStorage<number>(
    "elg.currentMaterial.v1",
    0,
  );
  const [history, setHistory] = useLocalStorage<Budget[]>(
    "elg.history.v1",
    [],
  );
  const [onboardingDone, setOnboardingDone] = useLocalStorage<boolean>(
    "elg.onboardingDone.v1",
    false,
  );

  const [tab, setTab] = useState<string>("budget");
  const [editingBudgetNumber, setEditingBudgetNumber] = useState(false);
  const [editingCounter, setEditingCounter] = useState(false);
  const [search, setSearch] = useState("");
  const [materialSearch, setMaterialSearch] = useState("");
  const [selectedMaterialForQty, setSelectedMaterialForQty] = useState<Material | null>(null);
  const [tempMaterialQty, setTempMaterialQty] = useState<string>("");
  const [editingService, setEditingService] = useState<string | null>(null);
  const [editingCatalogMaterial, setEditingCatalogMaterial] = useState<string | null>(null);
  const [materialPickerOpen, setMaterialPickerOpen] = useState(false);
  const [pulseId, setPulseId] = useState<string | null>(null);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [pickerSearch, setPickerSearch] = useState("");
  const [newBudgetConfirmOpen, setNewBudgetConfirmOpen] = useState(false);
  const [customDraftName, setCustomDraftName] = useState("");
  const [customDraftPrice, setCustomDraftPrice] = useState("");
  const [pdfOptionsOpen, setPdfOptionsOpen] = useState(false);
  const [pdfPreviewOpen, setPdfPreviewOpen] = useState(false);
  const [pdfPreview, setPdfPreview] = useState<PdfResult | null>(null);
  const [pdfPreviewPhone, setPdfPreviewPhone] = useState<string>("");
  const [pdfPreviewTitle, setPdfPreviewTitle] = useState<string>("");
  const [eyedropperFor, setEyedropperFor] = useState<"primary" | "accent" | null>(null);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [companySaved, setCompanySaved] = useState(false);

  const HISTORY_LIMIT = 20;

  const hasContactPicker =
    typeof navigator !== "undefined" &&
    // @ts-ignore
    typeof navigator.contacts?.select === "function";

  const itemsTotal = useMemo(
    () => items.reduce((s, it) => s + it.price * it.qty, 0),
    [items],
  );
  const total = itemsTotal + (laborCost || 0) + (materialCost || 0);

  const qtyByServiceId = useMemo(() => {
    const map: Record<string, number> = {};
    items.forEach((it) => {
      if (it.serviceId) map[it.serviceId] = (map[it.serviceId] ?? 0) + it.qty;
    });
    return map;
  }, [items]);

  const addServiceToBudget = (s: Service) => {
    setItems((prev) => {
      const existing = prev.find((it) => it.serviceId === s.id);
      if (existing) {
        return prev.map((it) =>
          it.id === existing.id ? { ...it, qty: it.qty + 1 } : it,
        );
      }
      return [
        ...prev,
        { id: uid(), serviceId: s.id, name: s.name, price: s.price, qty: 1, unit: s.unit },
      ];
    });
    setPulseId(s.id);
    window.setTimeout(() => setPulseId((cur) => (cur === s.id ? null : cur)), 350);
    toast.success(`${s.name} adicionado`, {
      description: "Item adicionado ao contrato",
      duration: 2000,
    });
  };


  const updateItem = (id: string, patch: Partial<BudgetItem>) => {
    setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)));
  };

  const removeItem = (id: string) => {
    setItems((prev) => prev.filter((it) => it.id !== id));
  };

  const saveToHistory = (b: Budget) => {
    setHistory((prev) => [b, ...prev].slice(0, HISTORY_LIMIT));
  };

  useEffect(() => {
    document.title = "Eletri-Pro — Contratos de Prestação de Serviços";
    const desc = "Crie contratos profissionais de prestação de serviços elétricos em segundos.";
    const meta = document.querySelector('meta[name="description"]');
    if (meta) meta.setAttribute("content", desc);
  }, []);

  const buildBudget = (): Budget => ({
    id: uid(),
    number: budgetNumber ?? counter,
    createdAt: new Date().toISOString(),
    client,
    items,
    kind,
    laborCost: laborCost > 0 ? laborCost : undefined,
    materialCost: materialCost > 0 ? materialCost : undefined,
    observations,
    materials: observations,
    materialProvidedByClient,
    execution,
    paymentConditions,
    startDate,
    endDate,
    clauses,
    city: cityOverride || company.city,
    state: company.state,
  });


  const ensureReady = () => {
    if (items.length === 0 && laborCost <= 0 && materialCost <= 0) {
      toast.error("Adicione um serviço ou mão de obra.");
      return false;
    }
    return true;
  };

  const handlePDF = async () => {
    if (!ensureReady()) return;
    setPdfPreview(null);
    setPdfPreviewOpen(true);
    try {
      const { exportBudgetPDF } = await import("@/features/orcamento/exporters");
      const b = buildBudget();
      const result = await exportBudgetPDF(b, company, "a4");
      saveToHistory(b);
      setCounter((c) => c + 1);
      setPdfPreview(result);
      setPdfPreviewPhone(b.client.phone ?? "");
      setPdfPreviewTitle(`Contrato Nº ${String(b.number).padStart(4, "0")}`);
    } catch (error) {
      setPdfPreviewOpen(false);
    }
  };

  const newBudget = () => {
    setTab("budget");
    if (items.length === 0 && !client.name) {
      toast.success("Pronto para um novo contrato");
      return;
    }
    setNewBudgetConfirmOpen(true);
  };
  
  const resetForm = () => {
    setItems([]);
    setClient(emptyClient);
    setLaborCost(0);
    setMaterialCost(0);
    setObservations("");
    setMaterialProvidedByClient(false);
    setExecution(emptyExecution);
    setPaymentConditions("");
    setBudgetNumber(null);
    setCityOverride("");
  };


  const confirmNewBudget = () => {
    resetForm();
    setNewBudgetConfirmOpen(false);
  };

  const importContact = async () => {
    if (!hasContactPicker) return;
    try {
      // @ts-ignore
      const contacts = await navigator.contacts.select(["name", "tel"], { multiple: false });
      if (!contacts || contacts.length === 0) return;
      const c = contacts[0];
      const name = Array.isArray(c.name) ? c.name[0] : c.name;
      const tel = Array.isArray(c.tel) ? c.tel[0] : c.tel;
      setClient({
        ...client,
        name: name || client.name,
        phone: (tel as string) || client.phone,
      });
    } catch {}
  };

  const addNewService = () => {
    const s: Service = { id: uid(), name: "Novo serviço", price: 0, unit: "un" };
    setServices((prev) => [s, ...prev]);
    setEditingService(s.id);
  };

  const updateService = (id: string, patch: Partial<Service>) => {
    setServices((prev) => prev.map((s) => (s.id === id ? { ...s, ...patch } : s)));
  };

  const removeService = (id: string) => {
    if (!confirm("Remover este serviço do catálogo?")) return;
    setServices((prev) => prev.filter((s) => s.id !== id));
  };

  const updateCatalogMaterial = (id: string, patch: Partial<Material>) => {
    setCatalogMaterials((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m)));
  };

  const removeCatalogMaterial = (id: string) => {
    if (!confirm("Remover este material do catálogo?")) return;
    setCatalogMaterials((prev) => prev.filter((m) => m.id !== id));
  };

  const addNewCatalogMaterial = () => {
    const m: Material = { id: uid(), name: "Novo material", unit: "un" };
    setCatalogMaterials((prev) => [m, ...prev]);
    setEditingCatalogMaterial(m.id);
  };

  const filteredServices = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return services;
    return services.filter((s) => s.name.toLowerCase().includes(q));
  }, [services, search]);

  const filteredCatalogMaterials = useMemo(() => {
    const q = materialSearch.trim().toLowerCase();
    if (!q) return catalogMaterials;
    return catalogMaterials.filter((m) => m.name.toLowerCase().includes(q));
  }, [catalogMaterials, materialSearch]);

  const handleMaterialClick = (m: Material) => {
    setSelectedMaterialForQty(m);
    setTempMaterialQty(m.defaultQty ? String(m.defaultQty) : "1");
  };

  const addMaterialToBudget = (m: Material, qtyOverride?: number) => {
    const qty = qtyOverride !== undefined ? qtyOverride : m.defaultQty;
    const qtyStr = qty ? `${qty} ` : "";
    const obsStr = m.observation ? ` (${m.observation})` : "";
    const newLine = `${qtyStr}${m.unit} ${m.name}${obsStr}`;
    setObservations((prev) => {
      const current = prev.trim();
      if (!current) return newLine;
      return current + "\n" + newLine;
    });
    setPulseId(m.id);
    window.setTimeout(() => setPulseId((cur) => (cur === m.id ? null : cur)), 350);
    toast.success(`${m.name} adicionado`);
    setSelectedMaterialForQty(null);
    setTempMaterialQty("");
  };

  const handleLogo = (file?: File) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {
      const dataUrl = reader.result as string;
      const colors = await extractBrandColors(dataUrl);
      setCompany((c) => ({
        ...c,
        logoDataUrl: dataUrl,
        ...(colors && {
          brandColor: colors.primary,
          brandColorAccent: colors.accent,
          logoBackground: colors.background ?? undefined,
          logoAspectRatio: colors.aspectRatio,
        }),
      }));
    };
    reader.readAsDataURL(file);
  };

  useEffect(() => {
    if (onboardingDone) window.scrollTo(0, 0);
  }, [onboardingDone]);

  useEffect(() => {
    if (onboardingDone) {
      window.history.pushState(null, "", location.href);
      const onPopState = () => {
        window.history.pushState(null, "", location.href);
        toast.info("Você já está no sistema de contratos", {
          description: "Use o botão de novo contrato se precisar limpar os dados.",
          duration: 2000
        });
      };
      window.addEventListener("popstate", onPopState);
      return () => window.removeEventListener("popstate", onPopState);
    }
  }, [onboardingDone]);

  return (
    <div className="flex min-h-dvh flex-col bg-background text-foreground overflow-hidden selection:bg-primary/20">
      {!onboardingDone && (
        <Onboarding
          company={company}
          setCompany={(updater) => setCompany(updater)}
          onDone={() => setOnboardingDone(true)}
        />
      )}

      <header className="sticky top-0 z-30 border-b border-border/60 bg-background/85 backdrop-blur pt-[env(safe-area-inset-top)] isolate">
        <div className="mx-auto flex max-w-3xl items-center justify-between gap-2 px-4 py-3">
          <div className="flex items-center gap-2">
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-accent text-accent-foreground shadow-yellow-lg border border-accent/20 animate-pulse-glow">
              <ShieldCheck className="h-5 w-5" />
            </span>
            <div className="flex flex-col">
              <h1 className="text-sm font-bold tracking-tight font-serif-juridico italic leading-none">Eletri-Pro</h1>
              <p className="text-[9px] uppercase tracking-[0.3em] text-primary/60 font-black mt-1.5 flex items-center gap-1.5">
                <span className="h-1 w-1 rounded-full bg-accent" />
                Contratos Profissionais
              </p>
            </div>
          </div>
          
          <div className="flex items-center gap-1">
            <div className="mr-2 flex items-center gap-1.5 border-r border-border/60 pr-2">
              {editingBudgetNumber ? (
                <Input
                  type="number"
                  autoFocus
                  className="h-7 w-20 px-1 py-0 text-xs font-bold"
                  value={budgetNumber ?? counter}
                  onChange={(e) => setBudgetNumber(parseInt(e.target.value) || 0)}
                  onBlur={() => setEditingBudgetNumber(false)}
                  onKeyDown={(e) => e.key === "Enter" && setEditingBudgetNumber(false)}
                />
              ) : (
                <button
                  type="button"
                  onClick={() => setEditingBudgetNumber(true)}
                  className="flex items-center gap-1 text-[11px] font-bold text-muted-foreground hover:text-foreground transition-colors font-serif-juridico"
                >
                  Nº {String(budgetNumber ?? counter).padStart(4, "0")}
                  <Pencil className="h-3 w-3 opacity-50" />
                </button>
              )}
            </div>
            <Button variant="ghost" size="icon" onClick={() => setHistoryOpen(true)} className="relative h-9 w-9 text-primary/70">
              <Clock className="h-4 w-4" />
              {history.length > 0 && (
                <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-accent px-1 text-[9px] font-black text-accent-foreground shadow-sm">
                  {history.length}
                </span>
              )}
            </Button>
            <div className="h-4 w-px bg-border/60 mx-1" />
            <Button variant="ghost" size="icon" onClick={newBudget} className="h-9 w-9">
              <Plus className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-3xl w-full px-4 pb-32 pt-4 overflow-hidden">
        <Tabs value={tab} onValueChange={setTab} className="w-full">
          <TabsList className="grid w-full grid-cols-4 bg-muted p-1 rounded-xl mb-6 shadow-sm border border-border/60 h-auto">
            <TabsTrigger value="budget" className="flex flex-col sm:flex-row items-center justify-center gap-1.5 sm:gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow-sm data-[state=active]:ring-1 data-[state=active]:ring-accent/30 transition-all h-auto py-2.5 px-2">
              <FileText className="h-4 w-4" />
              <span className="text-[10px] sm:text-xs font-bold font-sans uppercase tracking-tight">Contrato</span>
            </TabsTrigger>
            <TabsTrigger value="services" className="flex flex-col sm:flex-row items-center justify-center gap-1.5 sm:gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow-sm data-[state=active]:ring-1 data-[state=active]:ring-accent/30 transition-all h-auto py-2.5 px-2">
              <ListChecks className="h-4 w-4" />
              <span className="text-[10px] sm:text-xs font-bold font-sans uppercase tracking-tight">Catálogo</span>
            </TabsTrigger>
            <TabsTrigger value="clauses" className="flex flex-col sm:flex-row items-center justify-center gap-1.5 sm:gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow-sm data-[state=active]:ring-1 data-[state=active]:ring-accent/30 transition-all h-auto py-2.5 px-2">
              <ShieldCheck className="h-4 w-4" />
              <span className="text-[10px] sm:text-xs font-bold font-sans uppercase tracking-tight">Cláusulas</span>
            </TabsTrigger>
            <TabsTrigger value="company" className="flex flex-col sm:flex-row items-center justify-center gap-1.5 sm:gap-2 rounded-lg data-[state=active]:bg-background data-[state=active]:text-primary data-[state=active]:shadow-sm data-[state=active]:ring-1 data-[state=active]:ring-accent/30 transition-all h-auto py-2.5 px-2">
              <Settings className="h-4 w-4" />
              <span className="text-[10px] sm:text-xs font-bold font-sans uppercase tracking-tight">Ajustes</span>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="budget" className="mt-6 space-y-7 sm:space-y-8">
            <section className="space-y-3">
              <div className="flex items-center justify-between">
                <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                  <span className="h-3 w-1 bg-accent rounded-full" />
                  Contratante
                </h2>
                {hasContactPicker && (
                  <Button size="sm" variant="ghost" onClick={importContact} className="h-7 text-xs text-primary">
                    <Contact className="h-3.5 w-3.5 mr-1" /> Dos contatos
                  </Button>
                )}
              </div>
              <div className="grid grid-cols-1 gap-2.5">
                <Input placeholder="Nome completo do contratante" value={client.name} onChange={(e) => setClient({ ...client, name: e.target.value })} className="h-11" />
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                  <Input placeholder="Telefone (WhatsApp)" value={client.phone} onChange={(e) => setClient({ ...client, phone: formatPhoneBR(e.target.value) })} maxLength={16} className="h-11" />
                  <div className="relative group">
                    <Input 
                      placeholder={client.documentType === 'CNPJ' ? "00.000.000/0000-00" : "000.000.000-00"} 
                      value={client.document || ''}
                      onChange={(e) => setClient({ ...client, document: formatDocumentBR(e.target.value, client.documentType) })} 
                      maxLength={client.documentType === 'CNPJ' ? 18 : 14} 
                      className="h-11 pr-16" 
                    />
                    <div className="absolute right-1 top-1 bottom-1 flex items-center gap-0.5 bg-muted/50 rounded-md px-1 border border-border/50">
                      <button 
                        type="button"
                        onClick={() => setClient({ ...client, documentType: 'CPF', document: '' })}
                        className={`text-[9px] font-black px-1.5 py-1 rounded transition-colors ${(!client.documentType || client.documentType === 'CPF') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-primary'}`}
                      >
                        CPF
                      </button>
                      <button 
                        type="button"
                        onClick={() => setClient({ ...client, documentType: 'CNPJ', document: '' })}
                        className={`text-[9px] font-black px-1.5 py-1 rounded transition-colors ${client.documentType === 'CNPJ' ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-primary'}`}
                      >
                        CNPJ
                      </button>
                    </div>
                  </div>
                </div>
                <Input placeholder="Endereço da execução do serviço" value={client.address} onChange={(e) => setClient({ ...client, address: e.target.value })} className="h-11" />
              </div>
            </section>

            <section className="space-y-3">
              <div className="flex items-center justify-between">
                <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                  <span className="h-3 w-1 bg-accent rounded-full" />
                  Serviços
                </h2>
                <Button size="sm" variant="ghost" onClick={() => setPickerOpen(true)} className="h-7 text-xs text-primary">
                  <Plus className="h-3.5 w-3.5 mr-1" /> Adicionar
                </Button>
              </div>
              {items.length === 0 ? (
                <button onClick={() => setPickerOpen(true)} className="flex w-full flex-col items-center gap-3 rounded-2xl border-2 border-dashed border-primary/10 bg-muted/30 py-12 transition-all hover:bg-primary/5 hover:border-primary/30 group active:scale-[0.98]">
                  <div className="relative">
                    <div className="absolute inset-0 bg-accent/20 blur-xl rounded-full group-hover:bg-accent/40 transition-colors" />
                    <Plus className="relative h-12 w-12 text-primary bg-background rounded-full p-3 shadow-sm border border-border group-hover:scale-110 transition-transform" />
                  </div>
                  <div className="text-center">
                    <span className="block text-sm font-bold text-primary">Adicionar Primeiro Serviço</span>
                    <span className="block text-[10px] text-muted-foreground mt-1">Selecione do catálogo ou crie um novo</span>
                  </div>
                </button>
              ) : (
                <ul className="divide-y divide-border/60 rounded-xl bg-card border shadow-sm overflow-hidden">
                  {items.map((it) => (
                    <li key={it.id} className="p-3 bg-white/50">
                      <div className="flex items-center justify-between mb-2">
                        <Input 
                          value={it.name} 
                          onChange={(e) => updateItem(it.id, { name: e.target.value })} 
                          className="h-9 border-transparent bg-transparent font-bold text-sm focus:bg-white focus:border-border px-1" 
                        />
                        <Button size="icon" variant="ghost" onClick={() => removeItem(it.id)} className="h-8 w-8 text-destructive/70 hover:text-destructive hover:bg-destructive/5"><Trash2 className="h-4 w-4" /></Button>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="flex items-center rounded-lg border bg-background shadow-sm overflow-hidden h-9">
                          <button onClick={() => updateItem(it.id, { qty: Math.max(1, it.qty - 1) })} className="px-3 text-primary font-bold hover:bg-primary/5 active:bg-primary/10 transition-colors">−</button>
                          <span className="min-w-[32px] text-center text-xs font-black">{it.qty}</span>
                          <button onClick={() => updateItem(it.id, { qty: it.qty + 1 })} className="px-3 text-primary font-bold hover:bg-primary/5 active:bg-primary/10 transition-colors">+</button>
                        </div>
                        <div className="relative flex-1">
                          <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-[10px] font-bold text-muted-foreground">R$</span>
                          <Input 
                            type="number"
                            value={it.price} 
                            onChange={(e) => updateItem(it.id, { price: parseFloat(e.target.value) || 0 })} 
                            className="h-9 pl-8 text-sm font-semibold" 
                          />
                        </div>
                        <div className="text-right min-w-[80px]">
                          <p className="text-[10px] uppercase font-black text-muted-foreground leading-none mb-1">Total</p>
                          <p className="text-sm font-bold text-primary">{formatBRL(it.price * it.qty)}</p>
                        </div>
                      </div>
                    </li>
                  ))}
                  <li className="p-3 bg-muted/20 border-t flex justify-between items-center">
                    <span className="text-xs font-black uppercase text-primary/70">Total dos Serviços</span>
                    <span className="text-lg font-black text-primary">{formatBRL(itemsTotal)}</span>
                  </li>
                </ul>

              )}
            </section>

            <section className="space-y-4 pt-4 border-t">
              <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                <span className="h-3 w-1 bg-accent rounded-full" />
                Execução, Pagamento e Local
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-3">
                  <Input placeholder="Prazo (Ex: 5 dias úteis)" value={execution.estimatedDeadline} onChange={(e) => setExecution({...execution, estimatedDeadline: e.target.value})} />
                  <div className="grid grid-cols-2 gap-2">
                    <Input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
                    <Input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} title="Data de Término" />
                  </div>
                  <Input 
                    placeholder={`Cidade do Contrato (Padrão: ${company.city || 'Florianópolis'})`} 
                    value={cityOverride} 
                    onChange={(e) => setCityOverride(e.target.value)} 
                    className="h-10 text-xs"
                  />
                </div>
                <div className="space-y-3">
                  <Textarea placeholder="Condições de pagamento (Ex: 50% entrada e 50% no término)" value={paymentConditions} onChange={(e) => setPaymentConditions(e.target.value)} className="min-h-[145px]" />
                </div>
              </div>

            </section>

            <section className="space-y-4">
              <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                <span className="h-3 w-1 bg-accent rounded-full" />
                Materiais e Observações
              </h2>
              <div className="grid grid-cols-1 gap-3">
                <div className="flex items-center gap-3 p-3 rounded-xl bg-muted/40 border border-border/50 transition-colors hover:bg-muted/60">
                  <ToggleSwitch checked={materialProvidedByClient} onChange={() => setMaterialProvidedByClient(!materialProvidedByClient)} label="Material por conta do cliente" />
                  <div className="flex flex-col">
                    <span className="text-xs font-bold text-primary">Materiais por conta do CONTRATANTE</span>
                    <span className="text-[10px] text-muted-foreground leading-none mt-1">Cliente fornece os insumos necessários</span>
                  </div>
                </div>
                <Button variant="outline" size="lg" onClick={() => setMaterialPickerOpen(true)} className="w-full bg-background border-dashed border-2 border-primary/10 hover:border-primary/30 hover:bg-primary/5 h-12 text-xs font-bold">
                  <Package className="h-4 w-4 mr-2 text-accent" /> ACESSAR CATÁLOGO DE MATERIAIS
                </Button>
              </div>
              <Textarea placeholder="Observações adicionais..." value={observations} onChange={(e) => setObservations(e.target.value)} className="min-h-[120px]" />
            </section>
          </TabsContent>

          <TabsContent value="services" className="mt-4 space-y-3">
            <div className="flex gap-2">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input placeholder="Buscar serviço…" value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
              </div>
              <Button onClick={addNewService} size="icon" variant="electric"><Plus className="h-4 w-4" /></Button>
            </div>
            {items.length > 0 && (
              <button onClick={() => setTab("budget")} className="flex w-full items-center justify-between rounded-lg border border-primary/40 bg-primary/10 px-3 py-2.5">
                <span className="flex items-center gap-2 text-sm font-medium">
                  <ShieldCheck className="h-4 w-4 text-primary" /> {items.reduce((s, it) => s + it.qty, 0)} serviços no contrato
                </span>
                <span className="font-bold text-primary">{formatBRL(total)} →</span>
              </button>
            )}
            <ul className="space-y-2">
              {filteredServices.map((s) => (
                <li key={s.id} className="rounded-xl border bg-card p-3 flex items-center justify-between hover:border-primary/30 transition-colors group">
                  <div onClick={() => addServiceToBudget(s)} className="cursor-pointer flex-1">
                    <p className="text-sm font-bold group-hover:text-primary transition-colors">{s.name}</p>
                    <p className="text-xs text-muted-foreground">{formatBRL(s.price)} / {s.unit}</p>
                  </div>
                  <div className="flex items-center gap-1">
                    <Button size="icon" variant="ghost" className="h-9 w-9 text-primary bg-primary/5 hover:bg-primary/10" onClick={() => addServiceToBudget(s)}>
                      <PlusCircle className="h-5 w-5" />
                    </Button>
                    <Button size="icon" variant="ghost" className="h-9 w-9" onClick={() => setEditingService(s.id)}>
                      <Pencil className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </li>
              ))}
            </ul>

          </TabsContent>

          <TabsContent value="clauses" className="mt-4 space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                <span className="h-3 w-1 bg-accent rounded-full" />
                Cláusulas do Contrato
              </h2>
              <Button variant="ghost" size="sm" onClick={() => setClauses(DEFAULT_CLAUSES)} className="text-primary text-xs">Restaurar Padrão</Button>
            </div>
            <div className="space-y-4">
              {clauses.map((clause, idx) => (
                <div key={clause.id} className="rounded-xl border bg-card p-4 space-y-3">
                  <Input value={clause.title} onChange={(e) => {
                    const newClauses = [...clauses];
                    newClauses[idx].title = e.target.value;
                    setClauses(newClauses);
                  }} className="font-bold border-transparent bg-transparent" />
                  <Textarea value={clause.content} onChange={(e) => {
                    const newClauses = [...clauses];
                    newClauses[idx].content = e.target.value;
                    setClauses(newClauses);
                  }} className="text-sm min-h-[80px]" />
                  <Button variant="ghost" size="sm" onClick={() => setClauses(clauses.filter(c => c.id !== clause.id))} className="text-destructive"><Trash2 className="h-4 w-4 mr-1" /> Remover</Button>
                </div>
              ))}
              <Button onClick={() => setClauses([...clauses, { id: uid(), title: "NOVA CLÁUSULA", content: "" }])} variant="outline" className="w-full border-dashed"><Plus className="mr-2 h-4 w-4" /> Adicionar Cláusula</Button>
            </div>
          </TabsContent>

          <TabsContent value="company" className="mt-4 space-y-6">
            <div className="space-y-3">
              <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                <span className="h-3 w-1 bg-accent rounded-full" />
                Dados Profissionais
              </h2>
              <Input placeholder="Nome / Razão Social" value={company.name} onChange={(e) => setCompany({ ...company, name: e.target.value })} />
              <div className="relative group">
                <Input 
                  placeholder={company.documentType === 'CNPJ' ? "00.000.000/0000-00" : "000.000.000-00"} 
                  value={company.document || ''}
                  onChange={(e) => setCompany({ ...company, document: formatDocumentBR(e.target.value, company.documentType) })} 
                  maxLength={company.documentType === 'CNPJ' ? 18 : 14} 
                  className="pr-16" 
                />
                <div className="absolute right-1 top-1 bottom-1 flex items-center gap-0.5 bg-muted/50 rounded-md px-1 border border-border/50">
                  <button 
                    type="button"
                    onClick={() => setCompany({ ...company, documentType: 'CPF', document: '' })}
                    className={`text-[9px] font-black px-1.5 py-1 rounded transition-colors ${(!company.documentType || company.documentType === 'CPF') ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-primary'}`}
                  >
                    CPF
                  </button>
                  <button 
                    type="button"
                    onClick={() => setCompany({ ...company, documentType: 'CNPJ', document: '' })}
                    className={`text-[9px] font-black px-1.5 py-1 rounded transition-colors ${company.documentType === 'CNPJ' ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:text-primary'}`}
                  >
                    CNPJ
                  </button>
                </div>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Input placeholder="Telefone" value={company.phone} onChange={(e) => setCompany({ ...company, phone: formatPhoneBR(e.target.value) })} />
                <Input placeholder="E-mail" value={company.email} onChange={(e) => setCompany({ ...company, email: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <Input placeholder="Cidade" value={company.city} onChange={(e) => setCompany({ ...company, city: e.target.value })} />
                <Input placeholder="Estado" value={company.state} maxLength={2} onChange={(e) => setCompany({ ...company, state: e.target.value.toUpperCase() })} />
              </div>
            </div>
            

            
            <div className="space-y-3">
              <h2 className="text-[11px] font-black uppercase tracking-[0.2em] text-primary/80 flex items-center gap-2">
                <span className="h-3 w-1 bg-accent rounded-full" />
                Logotipo e Identidade
              </h2>
              <div className="flex flex-col items-center gap-4 p-6 rounded-2xl border-2 border-dashed border-border/60 bg-muted/20">
                {company.logoDataUrl ? (
                  <div className="relative group">
                    <img 
                      src={company.logoDataUrl} 
                      alt="Logo da Empresa" 
                      className="max-h-32 rounded-lg object-contain bg-white p-2 shadow-sm" 
                    />
                    <button 
                      onClick={() => setCompany(c => ({ ...c, logoDataUrl: undefined }))}
                      className="absolute -top-2 -right-2 h-6 w-6 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center shadow-lg opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </div>
                ) : (
                  <div className="flex flex-col items-center gap-2 text-center">
                    <div className="h-12 w-12 rounded-full bg-accent/10 flex items-center justify-center text-accent">
                      <Building2 className="h-6 w-6" />
                    </div>
                    <div className="space-y-1">
                      <p className="text-xs font-bold">Sem logotipo</p>
                      <p className="text-[10px] text-muted-foreground">Aparecerá no topo dos seus contratos</p>
                    </div>
                  </div>
                )}
                <input
                  type="file"
                  id="logo-upload"
                  accept="image/*"
                  className="hidden"
                  onChange={(e) => handleLogo(e.target.files?.[0])}
                />
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => document.getElementById("logo-upload")?.click()}
                  className="h-9 font-bold text-[10px] uppercase tracking-wider"
                >
                  {company.logoDataUrl ? "Trocar logotipo" : "Enviar logotipo"}
                </Button>
              </div>
            </div>

            <div className="rounded-xl border border-border bg-card/40 overflow-hidden">
              <button onClick={() => setPdfOptionsOpen(!pdfOptionsOpen)} className="w-full flex items-center justify-between p-3">
                <span className="flex items-center gap-2 text-sm font-semibold"><Info className="h-4 w-4" /> Opções do Contrato</span>
                <ChevronDown className={`h-4 w-4 transition-transform ${pdfOptionsOpen ? "rotate-180" : ""}`} />
              </button>
              {pdfOptionsOpen && (
                <div className="p-3 space-y-3 border-t">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">Validade do contrato (dias)</span>
                    <Input type="number" value={company.validityDays} onChange={(e) => setCompany({...company, validityDays: parseInt(e.target.value) || 0})} className="w-20 h-9 text-right font-bold" />
                  </div>
                  <div className="flex items-center justify-between">
                    <div className="flex flex-col">
                      <span className="text-sm font-medium">Selo de Qualidade</span>
                      <span className="text-[10px] text-muted-foreground">Exibir selo de conformidade</span>
                    </div>
                    <ToggleSwitch checked={company.inmetroEnabled !== false} onChange={() => setCompany({...company, inmetroEnabled: !company.inmetroEnabled})} label="INMETRO" />
                  </div>
                  <div className="flex items-center justify-between pt-2 border-t border-border/40">
                    <div className="flex flex-col">
                      <span className="text-sm font-medium">Garantia Padrão</span>
                      <span className="text-[10px] text-muted-foreground">Dias de garantia legal/técnica</span>
                    </div>
                    <Input type="number" value={company.warrantyDays ?? 90} onChange={(e) => setCompany({...company, warrantyDays: parseInt(e.target.value) || 0})} className="w-20 h-9 text-right font-bold" />
                  </div>
                </div>
              )}
            </div>
            <Button onClick={() => { setCompanySaved(true); setTimeout(() => setCompanySaved(false), 2000); }} variant={companySaved ? "default" : "electric" } className="w-full h-12 font-bold uppercase tracking-widest">{companySaved ? "Configurações Salvas!" : "Salvar Configurações"}</Button>
          </TabsContent>
        </Tabs>
      </main>

      {/* Rodapé Fixo de Ação */}
      <div className="fixed bottom-0 left-0 right-0 z-20 border-t border-border bg-background/80 backdrop-blur-lg p-4 pb-[calc(1rem+env(safe-area-inset-bottom))]">
        <div className="mx-auto max-w-3xl flex gap-3">
          <Button onClick={handlePDF} variant="default" size="lg" className="flex-1 h-14 font-black uppercase tracking-widest shadow-xl bg-primary hover:bg-primary/95 hover:scale-[1.01] active:scale-[0.98] transition-all">
            <FileDown className="mr-2 h-5 w-5 text-accent animate-bolt" /> GERAR CONTRATO PDF
          </Button>
        </div>
      </div>

      <Dialog open={historyOpen} onOpenChange={setHistoryOpen}>
        <DialogContent className="max-w-md p-0">
          <DialogHeader className="p-5 pb-2">
            <DialogTitle className="flex items-center gap-2"><Clock className="h-5 w-5" /> Histórico</DialogTitle>
            <DialogDescription>Seus últimos contratos gerados</DialogDescription>
          </DialogHeader>
          <ul className="max-h-[60vh] overflow-y-auto px-3 pb-4 space-y-2">
            {history.map((b) => (
              <li key={b.id} className="p-3 border rounded-lg bg-muted/50 hover:bg-muted transition-colors group">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="text-xs font-bold">#{b.number} - {b.client.name}</p>
                    <p className="text-[10px] text-muted-foreground">{new Date(b.createdAt).toLocaleDateString()}</p>
                  </div>
                  <div className="flex gap-1">
                    <Button size="sm" variant="ghost" onClick={() => { 
                      resetForm();
                      setItems(b.items); 
                      setClient(b.client); 
                      setTab("budget"); 
                      setHistoryOpen(false); 
                    }}><RotateCcw className="h-3 w-3" /></Button>
                    <Button size="sm" variant="ghost" onClick={() => setHistory(history.filter(h => h.id !== b.id))} className="text-destructive"><Trash2 className="h-3 w-3" /></Button>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </DialogContent>
      </Dialog>

      <AlertDialog open={newBudgetConfirmOpen} onOpenChange={setNewBudgetConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Novo contrato?</AlertDialogTitle>
            <AlertDialogDescription>Isso limpará os dados atuais. Deseja continuar?</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Não</AlertDialogCancel>
            <AlertDialogAction onClick={confirmNewBudget}>Sim, novo contrato</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <PdfPreviewModal open={pdfPreviewOpen} onOpenChange={setPdfPreviewOpen} pdf={pdfPreview} title={pdfPreviewTitle} />
      
      <Dialog open={materialPickerOpen} onOpenChange={setMaterialPickerOpen}>
        <DialogContent className="max-w-md p-0 overflow-hidden">
          <DialogHeader className="p-4"><DialogTitle>Catálogo de Materiais</DialogTitle></DialogHeader>
          <div className="p-4 pt-0 space-y-4">
            <Input placeholder="Buscar material..." value={materialSearch} onChange={(e) => setMaterialSearch(e.target.value)} />
            <ul className="max-h-[50vh] overflow-y-auto space-y-2 pb-20 sm:pb-4">
              {filteredCatalogMaterials.map(m => (
                <li key={m.id} className="p-3 border rounded-lg hover:border-primary/30 hover:bg-primary/5 flex justify-between items-center group transition-all">
                  <div className="flex-1 cursor-pointer" onClick={() => addMaterialToBudget(m)}>
                    <p className="text-sm font-bold group-hover:text-primary transition-colors">{m.name}</p>
                    <p className="text-[10px] text-muted-foreground uppercase font-medium">{m.unit}</p>
                  </div>
                  <Button size="icon" variant="ghost" className="h-9 w-9 text-primary bg-primary/5" onClick={() => addMaterialToBudget(m)}>
                    <PlusCircle className="h-5 w-5" />
                  </Button>
                </li>
              ))}

            </ul>
          </div>
        </DialogContent>
      </Dialog>
      
      <Dialog open={pickerOpen} onOpenChange={setPickerOpen}>
        <DialogContent className="max-w-md p-0 overflow-hidden">
          <DialogHeader className="p-4">
            <DialogTitle>Catálogo de Serviços</DialogTitle>
          </DialogHeader>
          <div className="p-4 pt-0 space-y-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input 
                placeholder="Buscar serviço..." 
                value={pickerSearch} 
                onChange={(e) => setPickerSearch(e.target.value)} 
                className="pl-9"
              />
            </div>
            <ul className="max-h-[50vh] overflow-y-auto space-y-2 pb-20 sm:pb-4">
              {services.filter(s => s.name.toLowerCase().includes(pickerSearch.toLowerCase())).map(s => (
                <li key={s.id} className="p-3 border rounded-lg hover:border-primary/30 hover:bg-primary/5 flex justify-between items-center group transition-all">
                  <div className="flex-1 cursor-pointer" onClick={() => { addServiceToBudget(s); setPickerOpen(false); }}>
                    <p className="text-sm font-bold group-hover:text-primary transition-colors">{s.name}</p>
                    <p className="text-xs text-muted-foreground">{formatBRL(s.price)} / {s.unit}</p>
                  </div>
                  <Button size="icon" variant="ghost" className="h-9 w-9 text-primary bg-primary/5" onClick={() => { addServiceToBudget(s); setPickerOpen(false); }}>
                    <PlusCircle className="h-5 w-5" />
                  </Button>
                </li>
              ))}
              <Button 
                variant="outline" 
                className="w-full border-dashed mt-2" 
                onClick={() => { addNewService(); setPickerOpen(false); setTab("services"); }}
              >
                <Plus className="mr-2 h-4 w-4" /> Criar Novo Serviço
              </Button>
            </ul>
          </div>
        </DialogContent>
      </Dialog>

    </div>

  );
};

export default App;
