"use client";
// src/app/customers/[id]/edit/page.tsx
import { useEffect, useMemo, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AppShell } from "@/components/layout/AppShell";
import { Input, Select, Textarea, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { createContactFormSchema, type ContactFormValues } from "@/lib/validations";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";
import { EntityCustomFieldsFormInputs } from "@/components/custom-fields/EntityCustomFieldsSection";
import type { CustomFieldDefinitionDto } from "@/lib/customFields.shared";

export default function EditCustomerPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { t } = useLanguage();
  const [customer, setCustomer] = useState<any>(null);
  const [companies, setCompanies] = useState<{ id: string; name: string }[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const definitions = useMemo(
    () => (customer?.customFieldData?.definitions ?? []) as CustomFieldDefinitionDto[],
    [customer]
  );

  const contactFormSchemaResolved = useMemo(
    () => createContactFormSchema(t, definitions),
    [t, definitions]
  );

  const { register, handleSubmit, reset, formState: { errors } } = useForm<ContactFormValues>({
    resolver: zodResolver(contactFormSchemaResolved),
  });

  useEffect(() => {
    Promise.all([
      fetch(`/api/customers/${id}`).then(r => r.json()),
      fetch("/api/companies?pageSize=100").then(r => r.json()),
    ]).then(([cd, co]) => {
      setCustomer(cd.data);
      setCompanies(co.data?.items ?? []);
    }).catch(() => toast.error(t("toast.loadFailed"))).finally(() => setIsLoading(false));
  }, [id, t]);

  useEffect(() => {
    if (!customer) return;
    const defs = customer.customFieldData?.definitions ?? [];
    const cf: Record<string, string> = {};
    for (const d of defs) {
      cf[d.fieldName] = customer.customFieldData?.values?.[d.fieldName] ?? "";
    }
    reset({
      firstName: customer.firstName,
      lastName: customer.lastName,
      email: customer.email,
      phone: customer.phone ?? "",
      mobile: customer.mobile ?? "",
      whatsapp: customer.whatsapp ?? "",
      jobTitle: customer.jobTitle ?? "",
      department: customer.department ?? "",
      city: customer.city ?? "",
      country: customer.country ?? "",
      notes: customer.notes ?? "",
      accountId: customer.accountId ?? "",
      preferredLanguage: customer.preferredLanguage ?? "ar",
      isDecisionMaker: customer.isDecisionMaker ?? false,
      doNotEmail: customer.doNotEmail ?? false,
      doNotCall: customer.doNotCall ?? false,
      customFields: cf,
    });
  }, [customer, reset]);

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

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

  return (
    <AppShell breadcrumbs={[
      { label: t("nav.customers"), href: "/customers" },
      { label: customer ? `${customer.firstName} ${customer.lastName}` : t("contacts.title"), href: `/customers/${id}` },
      { label: t("common.breadcrumbEdit") },
    ]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold">
            {t("customers.pageEditTitle")} — {customer?.firstName} {customer?.lastName}
          </h1>
        </div>
        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("customers.formPersonal")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label={t("leads.firstName")} required error={errors.firstName?.message} {...register("firstName")} />
              <Input label={t("leads.lastName")} required error={errors.lastName?.message} {...register("lastName")} />
              <Input label={t("common.email")} required type="email" error={errors.email?.message} {...register("email")} />
              <Input label={t("common.phone")} {...register("phone")} />
              <Input label={t("common.jobTitle")} {...register("jobTitle")} />
              <Select label={t("common.company")} options={companies.map(c => ({ value: c.id, label: c.name }))} placeholder={t("customers.noAccount")} {...register("accountId")} />
              <EntityCustomFieldsFormInputs definitions={definitions} register={register} errors={errors} />
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>{t("customers.formLocation")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label={t("common.city")} {...register("city")} />
              <Input label={t("common.country")} {...register("country")} />
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>{t("customers.formNotes")}</CardTitle></CardHeader>
            <CardContent><Textarea rows={4} placeholder={t("customers.notesPlaceholder")} {...register("notes")} /></CardContent>
          </Card>
          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={() => router.back()} disabled={isSaving}>{t("common.cancel")}</Button>
            <Button type="submit" loading={isSaving}>{t("common.save")}</Button>
          </div>
        </form>
      </div>
    </AppShell>
  );
}
