"use client";
// src/components/leads/LeadForm.tsx
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { createLeadFormSchema, type LeadFormValues, type LeadInput } from "@/lib/validations";
import { Input, Select, Textarea, Button, Card, CardHeader, CardTitle, CardContent } from "@/components/ui/index";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useLanguage } from "@/i18n/LanguageContext";
import {
  LEAD_STATUS_LABELS,
  LEAD_STATUS_LABELS_AR,
  LEAD_SOURCE_LABELS,
  LEAD_SOURCE_LABELS_AR,
} from "@/lib/utils";
import type { CustomFieldDefinitionDto } from "@/lib/customFields.shared";
import { EntityCustomFieldsFormInputs } from "@/components/custom-fields/EntityCustomFieldsSection";

interface User {
  id: string;
  name: string;
  email: string;
}

interface LeadFormProps {
  defaultValues?: Partial<LeadInput>;
  /** Initial values for custom fields (e.g. when editing). Keys must match definitions. */
  defaultCustomFields?: Record<string, string>;
  customFieldDefinitions?: CustomFieldDefinitionDto[];
  onSubmit: (data: LeadFormValues) => Promise<void>;
  isLoading?: boolean;
  submitLabel?: string;
  /** Rendered inside the form before the save/cancel row */
  childrenBeforeActions?: ReactNode;
}

const CURRENCY_OPTIONS = [
  { value: "USD", label: "USD — US Dollar" },
  { value: "EUR", label: "EUR — Euro" },
  { value: "GBP", label: "GBP — British Pound" },
  { value: "SAR", label: "SAR — Saudi Riyal" },
  { value: "AED", label: "AED — UAE Dirham" },
  { value: "EGP", label: "EGP — Egyptian Pound" },
];

export function LeadForm({
  defaultValues,
  defaultCustomFields,
  customFieldDefinitions = [],
  onSubmit,
  isLoading,
  submitLabel,
  childrenBeforeActions,
}: LeadFormProps) {
  const [users, setUsers] = useState<User[]>([]);
  const { t, language } = useLanguage();
  const defs = customFieldDefinitions;

  const leadFormSchemaResolved = useMemo(() => createLeadFormSchema(t, defs), [t, defs]);

  const statusLabels = language === "ar" ? LEAD_STATUS_LABELS_AR : LEAD_STATUS_LABELS;
  const sourceLabels = language === "ar" ? LEAD_SOURCE_LABELS_AR : LEAD_SOURCE_LABELS;

  const STATUS_OPTIONS = useMemo(
    () => Object.entries(statusLabels).map(([value, label]) => ({ value, label })),
    [statusLabels]
  );

  const SOURCE_OPTIONS = useMemo(
    () => Object.entries(sourceLabels).map(([value, label]) => ({ value, label })),
    [sourceLabels]
  );

  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 mergedDefaults = useMemo(() => {
    const cf: Record<string, string> = {};
    for (const d of defs) {
      cf[d.fieldName] = defaultCustomFields?.[d.fieldName] ?? "";
    }
    return {
      status: "NEW" as const,
      source: "OTHER" as const,
      currency: "USD",
      score: 0,
      ...defaultValues,
      customFields: cf,
    } as LeadFormValues;
  }, [defaultValues, defaultCustomFields, defs]);

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

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

  useEffect(() => {
    fetch("/api/users/assignable?pageSize=100")
      .then((r) => r.json())
      .then((d) => setUsers(d.data?.items ?? []))
      .catch(() => {});
  }, []);

  const score = watch("score") ?? 0;
  const buttonLabel = submitLabel ?? t("leads.saveLead");

  return (
    <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>{t("leads.formBasicInfo")}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Input
            label={t("leads.firstName")}
            required
            placeholder={t("customers.phFirstName")}
            error={errors.firstName?.message}
            {...register("firstName")}
          />
          <Input
            label={t("leads.lastName")}
            required
            placeholder={t("customers.phLastName")}
            error={errors.lastName?.message}
            {...register("lastName")}
          />

          <EntityCustomFieldsFormInputs definitions={defs} register={register} errors={errors} />

          <Input
            label={t("common.email")}
            type="email"
            placeholder={t("customers.phEmail")}
            error={errors.email?.message}
            {...register("email")}
          />
          <Input
            label={t("common.phone")}
            type="tel"
            placeholder={t("customers.phPhone")}
            error={errors.phone?.message}
            {...register("phone")}
          />
          <Input
            label={t("common.company")}
            placeholder={t("leads.placeholderCompany")}
            error={errors.company?.message}
            {...register("company")}
          />
          <Input
            label={t("common.jobTitle")}
            placeholder={t("customers.phJobTitle")}
            error={errors.jobTitle?.message}
            {...register("jobTitle")}
          />
          <Input
            label={t("common.website")}
            type="url"
            placeholder={t("leads.placeholderWebsite")}
            error={errors.website?.message}
            {...register("website")}
          />
          <Select
            label={t("common.industry")}
            options={INDUSTRY_OPTIONS}
            placeholder={t("leads.selectIndustry")}
            error={errors.industry?.message}
            {...register("industry")}
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t("leads.formClassification")}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Select
            label={t("common.status")}
            required
            options={STATUS_OPTIONS}
            error={errors.status?.message}
            {...register("status")}
          />
          <Select
            label={t("common.source")}
            required
            options={SOURCE_OPTIONS}
            error={errors.source?.message}
            {...register("source")}
          />
          <div className="sm:col-span-2">
            <label className="text-sm font-medium text-foreground block mb-1.5">
              {t("leads.leadScore")}: <span className="text-primary font-bold">{score}</span>
            </label>
            <input
              type="range"
              min={0}
              max={100}
              step={5}
              className="w-full accent-primary"
              {...register("score", { valueAsNumber: true })}
            />
            <div className="flex justify-between text-xs text-muted-foreground mt-1">
              <span>0 — {t("leads.scoreCold")}</span>
              <span>50 — {t("leads.scoreWarm")}</span>
              <span>100 — {t("leads.scoreHot")}</span>
            </div>
          </div>
          <Select
            label={t("common.assignedTo")}
            options={users.map((u) => ({ value: u.id, label: u.name }))}
            placeholder={t("deals.unassigned")}
            error={errors.assignedToId?.message}
            {...register("assignedToId")}
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t("leads.formFinancial")}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Input
            label={t("common.budget")}
            type="number"
            min={0}
            step={100}
            placeholder="50000"
            error={errors.budget?.message}
            {...register("budget", { valueAsNumber: true })}
          />
          <Select
            label={t("common.currency")}
            options={CURRENCY_OPTIONS}
            error={errors.currency?.message}
            {...register("currency")}
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t("leads.formLocation")}</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <Input
            label={t("common.city")}
            placeholder={t("companies.phCity")}
            error={errors.city?.message}
            {...register("city")}
          />
          <Input
            label={t("common.country")}
            placeholder={t("companies.phCountry")}
            error={errors.country?.message}
            {...register("country")}
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>{t("leads.formNotes")}</CardTitle>
        </CardHeader>
        <CardContent>
          <Textarea
            placeholder={t("leads.notesPlaceholder")}
            rows={4}
            error={errors.notes?.message}
            {...register("notes")}
          />
        </CardContent>
      </Card>

      {childrenBeforeActions}

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