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

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

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

  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 accountFormSchemaResolved = useMemo(
    () => createAccountFormSchema(t, cfDefinitions),
    [t, cfDefinitions]
  );

  const mergedDefaults = useMemo(() => {
    const cf: Record<string, string> = {};
    for (const d of cfDefinitions) {
      cf[d.fieldName] = "";
    }
    return {
      name: "",
      nameAr: "",
      type: "CUSTOMER" as const,
      domain: "",
      website: "",
      industry: "",
      size: "",
      country: "",
      city: "",
      address: "",
      phone: "",
      email: "",
      notes: "",
      annualRevenue: undefined,
      currency: "USD",
      customFields: cf,
    } satisfies AccountFormValues;
  }, [cfDefinitions]);

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

  useEffect(() => {
    reset(mergedDefaults);
  }, [mergedDefaults, reset]);

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

  return (
    <AppShell breadcrumbs={[{ label: t("nav.companies"), href: "/companies" }, { label: t("companies.new") }]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-foreground">{t("companies.pageNewTitle")}</h1>
          <p className="text-sm text-muted-foreground mt-0.5">{t("companies.pageNewSubtitle")}</p>
        </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 placeholder={t("companies.phName")} className="sm:col-span-2" error={errors.name?.message} {...register("name")} />
              <Input label={t("companies.fieldDomain")} placeholder={t("companies.phDomain")} error={errors.domain?.message} {...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" placeholder={t("companies.phEmail")} error={errors.email?.message} {...register("email")} />
              <Input label={t("common.phone")} type="tel" placeholder={t("companies.phPhone")} {...register("phone")} />
              <EntityCustomFieldsFormInputs definitions={cfDefinitions} 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")} placeholder={t("companies.phCity")} {...register("city")} />
              <Input label={t("common.country")} placeholder={t("companies.phCountry")} {...register("country")} />
              <Input label={t("common.address")} placeholder={t("companies.phAddress")} 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} placeholder={t("companies.phRevenue")} 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" }]} {...register("currency")} />
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle>{t("companies.formNotes")}</CardTitle></CardHeader>
            <CardContent>
              <Textarea placeholder={t("companies.notesPlaceholder")} rows={3} {...register("notes")} />
            </CardContent>
          </Card>

          <div className="flex justify-end gap-3">
            <Button type="button" variant="outline" onClick={() => router.back()} disabled={isLoading}>{t("common.cancel")}</Button>
            <Button type="submit" loading={isLoading}>{t("companies.create")}</Button>
          </div>
        </form>
      </div>
    </AppShell>
  );
}
