"use client";
// src/app/deals/[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 { createOpportunityFormSchema, type DealFormValues } 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";

const CURRENCY_OPTIONS = [
  { value: "USD", label: "USD" }, { value: "EUR", label: "EUR" },
  { value: "GBP", label: "GBP" }, { value: "SAR", label: "SAR" }, { value: "AED", label: "AED" },
];

export default function EditDealPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { t } = useLanguage();
  const [deal, setDeal] = useState<any>(null);
  const [users, setUsers] = useState<any[]>([]);
  const [customers, setCustomers] = useState<any[]>([]);
  const [companies, setCompanies] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

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

  const dealFormSchemaResolved = useMemo(
    () => createOpportunityFormSchema(t, definitions),
    [t, definitions]
  );

  const STAGE_OPTIONS = useMemo(
    () => [
      { value: "QUALIFICATION", label: t("deals.stageQualification") },
      { value: "DISCOVERY", label: t("deals.stageDiscovery") },
      { value: "PROPOSAL", label: t("deals.stageProposal") },
      { value: "NEGOTIATION", label: t("deals.stageNegotiation") },
      { value: "CONTRACT", label: t("deals.stageContract") },
      { value: "CLOSED_WON", label: t("deals.stageClosedWon") },
      { value: "CLOSED_LOST", label: t("deals.stageClosedLost") },
    ],
    [t]
  );

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

  useEffect(() => {
    Promise.all([
      fetch(`/api/deals/${id}`).then(r => r.json()),
      fetch("/api/users/assignable?pageSize=100").then(r => r.json()),
      fetch("/api/customers?pageSize=200").then(r => r.json()),
      fetch("/api/companies?pageSize=200").then(r => r.json()),
    ]).then(([d, u, cu, co]) => {
      const dealData = d.data;
      setDeal(dealData);
      setUsers(u.data?.items ?? []);
      setCustomers(cu.data?.items ?? []);
      setCompanies(co.data?.items ?? []);
    }).catch(() => toast.error(t("toast.loadFailed"))).finally(() => setIsLoading(false));
  }, [id, t]);

  useEffect(() => {
    if (!deal) return;
    const defs = deal.customFieldData?.definitions ?? [];
    const cf: Record<string, string> = {};
    for (const d of defs) {
      cf[d.fieldName] = deal.customFieldData?.values?.[d.fieldName] ?? "";
    }
    reset({
      title: deal.title,
      value: Number(deal.value),
      currency: deal.currency,
      stage: deal.stage,
      probability: deal.probability,
      closeDate: deal.closeDate ? deal.closeDate.slice(0, 10) : "",
      notes: deal.notes ?? "",
      assignedToId: deal.assignedToId ?? "",
      contactId: deal.contactId ?? "",
      accountId: deal.accountId ?? "",
      lostReason: deal.lostReason ?? "",
      pipelineId: deal.pipelineId ?? "",
      customFields: cf,
    });
  }, [deal, reset]);

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

  if (isLoading) return (
    <AppShell breadcrumbs={[{ label: t("nav.deals"), href: "/deals" }, { 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.deals"), href: "/deals" },
      { label: deal?.title ?? t("deals.title"), href: `/deals/${id}` },
      { label: t("common.breadcrumbEdit") },
    ]}>
      <div className="w-full min-w-0">
        <div className="mb-6">
          <h1 className="text-xl font-bold">{t("deals.editPageTitle")} — {deal?.title}</h1>
        </div>
        <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("deals.cardInfo")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Input label={t("deals.fieldTitle")} required className="sm:col-span-2" error={errors.title?.message} {...register("title")} />
              <Input label={t("deals.fieldValue")} required type="number" min={0} step={100} error={errors.value?.message} {...register("value", { valueAsNumber: true })} />
              <Select label={t("common.currency")} options={CURRENCY_OPTIONS} {...register("currency")} />
              <Select label={t("deals.stage")} required options={STAGE_OPTIONS} error={errors.stage?.message} {...register("stage")} />
              <Input label={t("deals.probability")} type="number" min={0} max={100} {...register("probability", { valueAsNumber: true })} />
              <Input label={t("deals.fieldClose")} type="date" {...register("closeDate")} />
              <Select label={t("deals.fieldAssigned")} options={users.map(u => ({ value: u.id, label: u.name }))} placeholder={t("deals.unassigned")} {...register("assignedToId")} />
              <EntityCustomFieldsFormInputs definitions={definitions} register={register} errors={errors} />
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>{t("deals.relatedTo")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <Select label={t("deals.fieldCustomer")} options={customers.map(c => ({ value: c.id, label: `${c.firstName} ${c.lastName}` }))} placeholder={t("deals.selectCustomer")} {...register("contactId")} />
              <Select label={t("deals.fieldCompany")} options={companies.map(c => ({ value: c.id, label: c.name }))} placeholder={t("deals.selectCompany")} {...register("accountId")} />
            </CardContent>
          </Card>
          <Card>
            <CardHeader><CardTitle>{t("deals.cardNotes")}</CardTitle></CardHeader>
            <CardContent>
              <Textarea rows={3} placeholder={t("deals.notesPh")} {...register("notes")} />
              <div className="mt-3">
                <Input label={t("deals.lostReason")} placeholder={t("deals.lostReasonPh")} {...register("lostReason")} />
              </div>
            </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>
  );
}
