"use client";
// src/app/companies/[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 { createAccountFormSchema, type AccountFormValues } 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 EditCompanyPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { t } = useLanguage();
  const [company, setCompany] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

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

  const accountFormSchemaResolved = useMemo(
    () => createAccountFormSchema(t, definitions),
    [t, definitions]
  );

  const SIZE_OPTIONS = useMemo(
    () => [
      { value: "1-10", label: t("companies.size1_10") },
      { value: "11-50", label: t("companies.size11_50") },
      { value: "51-200", label: t("companies.size51_200") },
      { value: "201-500", label: t("companies.size201_500") },
      { value: "501-1000", label: t("companies.size501_1000") },
      { value: "1001+", label: t("companies.size1001p") },
    ],
    [t]
  );

  const INDUSTRY_OPTIONS = useMemo(
    () => [
      { value: "Technology", label: t("companies.indTech") },
      { value: "Healthcare", label: t("companies.indHealth") },
      { value: "Finance", label: t("companies.indFinance") },
      { value: "Education", label: t("companies.indEducation") },
      { value: "Retail", label: t("companies.indRetail") },
      { value: "Manufacturing", label: t("companies.indManufacturing") },
      { value: "Real Estate", label: t("companies.indRealEstate") },
      { value: "Media", label: t("companies.indMedia") },
      { value: "Consulting", label: t("companies.indConsulting") },
      { value: "Other", label: t("companies.indOther") },
    ],
    [t]
  );

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

  useEffect(() => {
    fetch(`/api/companies/${id}`)
      .then((r) => r.json())
      .then((d) => {
        const c = d.data;
        setCompany(c);
      })
      .catch(() => toast.error(t("toast.loadFailed")))
      .finally(() => setIsLoading(false));
  }, [id, t]);

  useEffect(() => {
    if (!company) return;
    const defs = company.customFieldData?.definitions ?? [];
    const cf: Record<string, string> = {};
    for (const d of defs) {
      cf[d.fieldName] = company.customFieldData?.values?.[d.fieldName] ?? "";
    }
    reset({
      name: company.name,
      domain: company.domain ?? "",
      website: company.website ?? "",
      industry: company.industry ?? "",
      size: company.size ?? "",
      city: company.city ?? "",
      country: company.country ?? "",
      address: company.address ?? "",
      phone: company.phone ?? "",
      email: company.email ?? "",
      notes: company.notes ?? "",
      annualRevenue: company.annualRevenue != null ? Number(company.annualRevenue) : undefined,
      currency: company.currency ?? "USD",
      customFields: cf,
    });
  }, [company, reset]);

  const onSubmit = async (data: AccountFormValues) => {
    setIsSaving(true);
    try {
      const { customFields, ...rest } = data;
      const payload: Record<string, unknown> = { ...rest };
      if (definitions.length) {
        payload.customFields = customFields;
      }
      const res = await fetch(`/api/companies/${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.companyUpdated"));
      router.push(`/companies/${id}`);
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) return (
    <AppShell breadcrumbs={[{ label: t("nav.companies"), href: "/companies" }, { 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.companies"), href: "/companies" },
      { label: company?.name ?? t("companies.title"), href: `/companies/${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("companies.pageEditTitle")} — {company?.name}</h1>
        </div>

        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("companies.formCompanyInfo")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label={t("companies.fieldName")} required className="sm:col-span-2"
                error={errors.name?.message} {...register("name")} />
              <Input label={t("companies.fieldDomain")} placeholder={t("companies.phDomain")} {...register("domain")} />
              <Input label={t("common.website")} type="url" placeholder={t("companies.phWebsite")}
                error={errors.website?.message} {...register("website")} />
              <Select label={t("common.industry")} options={INDUSTRY_OPTIONS} placeholder={t("companies.selectIndustry")} {...register("industry")} />
              <Select label={t("companies.fieldSize")} options={SIZE_OPTIONS} placeholder={t("companies.selectSize")} {...register("size")} />
              <Input label={t("common.email")} type="email" {...register("email")} />
              <Input label={t("common.phone")} type="tel" {...register("phone")} />
              <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")} />
              <Input label={t("common.address")} className="sm:col-span-2" {...register("address")} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle>{t("companies.formFinancial")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label={t("companies.fieldAnnualRevenue")} type="number" min={0}
                error={errors.annualRevenue?.message}
                {...register("annualRevenue", { valueAsNumber: true })} />
              <Select label={t("common.currency")} options={[
                { value: "USD", label: "USD" }, { value: "EUR", label: "EUR" },
                { value: "GBP", label: "GBP" }, { value: "SAR", label: "SAR" },
                { value: "AED", label: "AED" },
              ]} {...register("currency")} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle>{t("companies.formNotes")}</CardTitle></CardHeader>
            <CardContent>
              <Textarea rows={3} placeholder={t("companies.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>
  );
}
