"use client";
// src/app/leads/new/page.tsx
import { 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 { useState, useEffect } from "react";
import { useLanguage } from "@/i18n/LanguageContext";
import type { CustomFieldDefinitionDto } from "@/lib/customFields.shared";

export default function NewLeadPage() {
  const router = useRouter();
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const [cfDefinitions, setCfDefinitions] = useState<CustomFieldDefinitionDto[]>([]);

  useEffect(() => {
    fetch("/api/custom-fields?entity=Lead")
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((j) => {
        const defs = j.data?.definitions;
        if (!Array.isArray(defs)) return;
        setCfDefinitions(defs);
      })
      .catch(() => {
        /* no custom fields or no permission */
      });
  }, []);

  const handleSubmit = async (data: LeadFormValues) => {
    setIsLoading(true);
    try {
      const { customFields, ...leadData } = data;
      const payload: Record<string, unknown> = { ...leadData };
      if (cfDefinitions.length > 0) {
        payload.customFields = customFields;
      }
      const res = await fetch("/api/leads", {
        method: "POST",
        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"));
      }
      const result = await res.json();
      toast.success(t("toast.leadCreated"));
      router.push(`/leads/${result.data.id}`);
    } catch (err: any) {
      toast.error(err.message ?? t("error.serverError"));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <AppShell
      breadcrumbs={[
        { label: t("nav.leads"), href: "/leads" },
        { label: t("leads.new") },
      ]}
    >
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("leads.pageNewH1")}</h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            {t("leads.pageNewDesc")}
          </p>
        </div>
        <LeadForm
          customFieldDefinitions={cfDefinitions}
          onSubmit={handleSubmit}
          isLoading={isLoading}
          submitLabel={t("leads.createLead")}
        />
      </div>
    </AppShell>
  );
}
