"use client";
// src/app/leads/[id]/edit/page.tsx
import { useEffect, useMemo, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { AppShell } from "@/components/layout/AppShell";
import { LeadForm } from "@/components/leads/LeadForm";
import type { LeadFormValues } from "@/lib/validations";
import { toast } from "sonner";
import { Loader2, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";

export default function EditLeadPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { t } = useLanguage();
  const [lead, setLead] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetch(`/api/leads/${id}`)
      .then((r) => {
        if (!r.ok) throw new Error("NOT_FOUND");
        return r.json();
      })
      .then((d) => setLead(d.data))
      .catch(() => setError("NOT_FOUND"))
      .finally(() => setIsLoading(false));
  }, [id]);

  const defaultCustomFields = useMemo(() => {
    if (!lead?.customFieldData) return undefined;
    const { definitions, values } = lead.customFieldData;
    const o: Record<string, string> = {};
    for (const d of definitions) {
      o[d.fieldName] = values[d.fieldName] ?? "";
    }
    return o;
  }, [lead]);

  const leadFormDefaults = useMemo(
    () =>
      lead
        ? {
            firstName: lead.firstName,
            lastName: lead.lastName,
            email: lead.email ?? "",
            phone: lead.phone ?? "",
            company: lead.company ?? "",
            jobTitle: lead.jobTitle ?? "",
            status: lead.status,
            source: lead.source,
            score: lead.score,
            notes: lead.notes ?? "",
            website: lead.website ?? "",
            country: lead.country ?? "",
            city: lead.city ?? "",
            industry: lead.industry ?? "",
            budget: lead.budget ? Number(lead.budget) : undefined,
            currency: lead.currency,
            assignedToId: lead.assignedToId ?? "",
          }
        : undefined,
    [lead]
  );

  const handleSubmit = async (data: LeadFormValues) => {
    setIsSaving(true);
    try {
      const { customFields, ...leadData } = data;
      const payload: Record<string, unknown> = { ...leadData };
      if (lead?.customFieldData?.definitions?.length) {
        payload.customFields = customFields;
      }
      const res = await fetch(`/api/leads/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error ?? t("toast.failed"));
      }
      toast.success(t("toast.leadUpdated"));
      router.push(`/leads/${id}`);
    } catch (err: any) {
      toast.error(err.message ?? t("error.serverError"));
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <AppShell breadcrumbs={[{ label: t("nav.leads"), href: "/leads" }, { label: t("common.breadcrumbEdit") }]}>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      </AppShell>
    );
  }

  if (error || !lead) {
    return (
      <AppShell breadcrumbs={[{ label: t("nav.leads"), href: "/leads" }, { label: t("common.breadcrumbNotFound") }]}>
        <div className="flex flex-col items-center justify-center h-64 gap-4">
          <AlertCircle className="w-12 h-12 text-destructive" />
          <p className="text-lg font-semibold">{error === "NOT_FOUND" ? t("leads.notFound") : error}</p>
          <Button variant="outline" onClick={() => router.push("/leads")}>
            {t("leads.backToLeads")}
          </Button>
        </div>
      </AppShell>
    );
  }

  return (
    <AppShell
      breadcrumbs={[
        { label: t("nav.leads"), href: "/leads" },
        { label: `${lead.firstName} ${lead.lastName}`, href: `/leads/${id}` },
        { label: t("common.breadcrumbEdit") },
      ]}
    >
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">
            {t("leads.edit")} — {lead.firstName} {lead.lastName}
          </h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            {t("leads.editSubtitle")}
          </p>
        </div>
        <LeadForm
          defaultValues={leadFormDefaults}
          defaultCustomFields={defaultCustomFields}
          customFieldDefinitions={lead.customFieldData?.definitions ?? []}
          onSubmit={handleSubmit}
          isLoading={isSaving}
          submitLabel={t("common.save")}
        />
      </div>
    </AppShell>
  );
}
