"use client";
// src/app/leads/[id]/convert/page.tsx
import { useEffect, useMemo, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardHeader, CardTitle, CardContent, Input, Select } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import { createLeadConvertSchema, type LeadConvertInput } from "@/lib/validations";
import { formNoValidateProps } from "@/lib/form";
import { toast } from "sonner";
import { Loader2, AlertCircle, ArrowLeft, Building2, Briefcase, UserRound } from "lucide-react";

export default function ConvertLeadPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { t, isRTL } = useLanguage();
  const { user } = useAuth();

  const [lead, setLead] = useState<any>(null);
  const [accounts, setAccounts] = useState<{ id: string; name: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const convertSchema = useMemo(() => createLeadConvertSchema(t), [t]);

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    reset,
    formState: { errors },
  } = useForm<LeadConvertInput>({
    resolver: zodResolver(convertSchema),
    defaultValues: {
      existingAccountId: "",
      createAccount: true,
      createOpportunity: true,
      opportunityTitle: "",
      opportunityValue: "",
    },
  });

  const existingAccountId = watch("existingAccountId");
  const createOpportunity = watch("createOpportunity");

  const accountOptions = useMemo(
    () => accounts.map((a) => ({ value: a.id, label: a.name })),
    [accounts]
  );

  const canConvert = user && hasPermission(user.role, "leads:update");

  useEffect(() => {
    if (existingAccountId) setValue("createAccount", false);
    else setValue("createAccount", true);
  }, [existingAccountId, setValue]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const leadRes = await fetch(`/api/leads/${id}`);
        if (!leadRes.ok) throw new Error("notfound");
        const ld = await leadRes.json();
        const l = ld.data;
        if (cancelled) return;
        setLead(l);
        if (l?.isConverted && l.contactId) {
          router.replace(`/customers/${l.contactId}`);
          router.refresh();
          return;
        }

        try {
          const compRes = await fetch("/api/companies?pageSize=500");
          if (compRes.ok) {
            const acc = await compRes.json();
            if (!cancelled) setAccounts(acc.data?.items ?? []);
          }
        } catch {
          /* قائمة الشركات اختيارية */
        }
      } catch {
        if (!cancelled) setError("load");
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [id, router]);

  useEffect(() => {
    if (!lead) return;
    reset({
      existingAccountId: "",
      createAccount: true,
      createOpportunity: true,
      opportunityTitle: `${lead.firstName} ${lead.lastName} — Opportunity`,
      opportunityValue: lead.budget != null ? String(lead.budget) : "",
    });
  }, [lead, reset]);

  const onSubmit = async (data: LeadConvertInput) => {
    if (!canConvert || !lead) return;
    setSubmitting(true);
    try {
      const body: Record<string, unknown> = {
        createOpportunity: data.createOpportunity,
        opportunityTitle: data.opportunityTitle.trim() || undefined,
        opportunityValue:
          data.opportunityValue === "" || data.opportunityValue === undefined
            ? undefined
            : Number(data.opportunityValue),
        createAccount: !data.existingAccountId && data.createAccount,
        existingAccountId: data.existingAccountId || undefined,
      };
      const res = await fetch(`/api/leads/${id}/convert`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (res.status === 409 && json.error === "CONTACT_EMAIL_IN_USE") {
          throw new Error(t("leads.convertEmailConflict"));
        }
        throw new Error(json.error ?? json.message ?? "Failed");
      }
      toast.success(t("leads.convertSuccess"));
      const payload = json.data as { contact?: { id?: string } } | undefined;
      const contactId = payload?.contact?.id;
      if (contactId) {
        router.replace(`/customers/${contactId}`);
      } else {
        router.replace("/leads");
      }
      router.refresh();
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t("error.serverError"));
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <AppShell
        breadcrumbs={[
          { label: t("nav.leads"), href: "/leads" },
          { label: "…" },
        ]}
      >
        <div className="flex justify-center py-24">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      </AppShell>
    );
  }

  if (error || !lead) {
    return (
      <AppShell breadcrumbs={[{ label: t("nav.leads"), href: "/leads" }]}>
        <div className="flex flex-col items-center justify-center py-16 gap-4">
          <AlertCircle className="w-12 h-12 text-destructive" />
          <p className="text-muted-foreground">{t("error.notFound")}</p>
          <Link
            href="/leads"
            className="inline-flex items-center justify-center h-9 px-4 text-sm font-medium rounded-lg border border-input bg-background hover:bg-accent"
          >
            {t("common.back")}
          </Link>
        </div>
      </AppShell>
    );
  }

  if (!canConvert) {
    return (
      <AppShell
        breadcrumbs={[
          { label: t("nav.leads"), href: "/leads" },
          { label: lead.firstName + " " + lead.lastName, href: `/leads/${id}` },
        ]}
      >
        <p className="text-destructive">{t("error.unauthorized")}</p>
        <Link href={`/leads/${id}`} className="text-primary text-sm mt-2 inline-block">
          {t("common.back")}
        </Link>
      </AppShell>
    );
  }

  return (
    <AppShell
      breadcrumbs={[
        { label: t("nav.leads"), href: "/leads" },
        { label: `${lead.firstName} ${lead.lastName}`, href: `/leads/${id}` },
        { label: t("leads.convertPageTitle") },
      ]}
    >
      <div className="w-full min-w-0">
        <Link
          href={`/leads/${id}`}
          className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mb-4"
        >
          <ArrowLeft className={isRTL ? "w-4 h-4 rotate-180" : "w-4 h-4"} />
          {t("common.back")}
        </Link>

        <h1 className="text-xl font-bold mb-1">{t("leads.convertPageTitle")}</h1>
        <p className="text-sm text-muted-foreground mb-6">{t("leads.convertPageDesc")}</p>

        <Card className="border-border/70 shadow-sm">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <UserRound className="w-5 h-5 text-primary" />
              <span>
                {lead.firstName} {lead.lastName}
              </span>
              {lead.company && (
                <span className="text-muted-foreground font-normal text-base">
                  · {lead.company}
                </span>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form {...formNoValidateProps} onSubmit={handleSubmit(onSubmit)} className="space-y-6">
              <div className="rounded-xl border border-border/70 bg-muted/30 p-4">
                <div className="flex items-center gap-2 mb-3">
                  <Building2 className="w-4 h-4 text-primary" />
                  <p className="text-sm font-semibold">{t("companies.title")}</p>
                </div>
                <Select
                  id="convert-existing-company"
                  label={t("leads.useExistingAccount")}
                  options={accountOptions}
                  placeholder={t("common.none")}
                  error={errors.existingAccountId?.message}
                  {...register("existingAccountId")}
                />
                {!existingAccountId && (
                  <label className="mt-3 flex items-center gap-2 text-sm cursor-pointer">
                    <input
                      type="checkbox"
                      {...register("createAccount")}
                      className="rounded border-input"
                    />
                    {t("leads.createCompanyAccount")}
                  </label>
                )}
              </div>

              <div className="rounded-xl border border-border/70 bg-muted/30 p-4">
                <div className="flex items-center gap-2 mb-3">
                  <Briefcase className="w-4 h-4 text-primary" />
                  <p className="text-sm font-semibold">{t("deals.title")}</p>
                </div>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input
                    type="checkbox"
                    {...register("createOpportunity")}
                    className="rounded border-input"
                  />
                  {t("leads.createOpportunity")}
                </label>

                {createOpportunity && (
                  <div className="space-y-3 mt-3 sm:ps-4 border-s-2 border-border">
                    <Input
                      id="convert-opp-title"
                      label={t("leads.oppTitle")}
                      required
                      error={errors.opportunityTitle?.message}
                      {...register("opportunityTitle")}
                    />
                    <Input
                      id="convert-opp-value"
                      label={t("leads.oppValue")}
                      type="number"
                      min={0}
                      step={100}
                      error={errors.opportunityValue?.message}
                      {...register("opportunityValue")}
                    />
                  </div>
                )}
              </div>

              <div
                className={`flex flex-col sm:flex-row gap-3 pt-2 ${
                  isRTL ? "sm:justify-end" : "sm:justify-start"
                }`}
              >
                <Button type="submit" loading={submitting} disabled={submitting} className="sm:min-w-[170px]">
                  {t("leads.convertSubmit")}
                </Button>
                <Link
                  href={`/leads/${id}`}
                  className="inline-flex items-center justify-center h-9 px-4 text-sm font-medium rounded-lg border border-input bg-background hover:bg-accent sm:min-w-[120px]"
                >
                  {t("common.cancel")}
                </Link>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </AppShell>
  );
}
