"use client";

import React, {
  useEffect,
  useState,
  useRef,
  ChangeEvent,
  useMemo,
} from "react";
import Select from "react-select";
import AsyncSelect from "react-select/async"; // ✅ NEW — for live city search
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import {
  createCompany,
  updateCompany,
  getCompany,
  COMPANIES_API_BASE_URL,
} from "@/lib/api/company.api";
import { fetchApi } from "@/lib/api/http";
import type { CreateCompanyDto } from "@/lib/api/types/company.types";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";

// ✅ Kept — worldwide cities dataset (used only as fallback for legacy values)
import { City } from "country-state-city";

// ─── Types ────────────────────────────────────────────────────────────────────
interface SelectOption {
  value: number | string;
  label: string;
}

export interface UploadedDocument {
  originalName: string;
  fileName: string;
  filePath: string;
  rawFile?: File;
}

// ─── Props ────────────────────────────────────────────────────────────────────
interface CompanyFormProps {
  isOpen: boolean;
  onClose: () => void;
  refreshData?: () => void;
  editId?: number | null;
  onSuccess?: (company: { id: number; name: string }) => void; // ✅ CHANGE 1 — added
}

// ─── Default state ────────────────────────────────────────────────────────────
const DEFAULT = {
  name: "",
  email: "",
  address: "",
  city: "",
  contact_person: "",
  designation: "",
  mobile: "",
  telephone: "",
  fax: "",
  validity: "",
  certification_body: "",
  client_group: "",
  accreditation: "",
  scope_of_work: "",
  reference_number: "",
  country_id: undefined as number | undefined,
  standard_ids: [] as number[],
  documents: [] as UploadedDocument[],
};

// ─── Validity options ─────────────────────────────────────────────────────────
const VALIDITY_OPTIONS: SelectOption[] = [
  { value: "1 Year", label: "1 Year" },
  { value: "2 Years", label: "2 Years" },
  { value: "3 Years", label: "3 Years" },
];
// ✅ NEW — Client Group options (which team manages this client)
const CLIENT_GROUP_OPTIONS: SelectOption[] = [
  { value: "QRS", label: "QRS" },
  { value: "TQS", label: "TQS" },
  { value: "QRS TEAM A", label: "QRS TEAM A" },
  { value: "QRS TEAM B", label: "QRS TEAM B" },
  { value: "Overseas", label: "Overseas" },
];

// ─── Component ────────────────────────────────────────────────────────────────
export default function CompanyForm({
  isOpen,
  onClose,
  refreshData,
  editId,
  onSuccess, // ✅ CHANGE 2 — added to destructure
}: CompanyFormProps) {
  const isEdit = Boolean(editId);
  const fileRef = useRef<HTMLInputElement>(null);
  const { visibleFieldKeys, isReady: permsReady } =
    useModulePermissions("companies");

  // 🎯 DEBUG
  console.log(
    "🎯 [FORM] permsReady:",
    permsReady,
    "visibleFieldKeys:",
    visibleFieldKeys,
  );

  const showField = (key: string): boolean => {
    if (!permsReady) return true; // still loading → show everything
    if (!visibleFieldKeys) return true;
    return visibleFieldKeys.includes(key);
  };

  const [form, setForm] = useState({ ...DEFAULT });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState(false);
  const [loadingEdit, setLoadingEdit] = useState(false);

  const [countriesList, setCountriesList] = useState<SelectOption[]>([]);
  const [standardsList, setStandardsList] = useState<SelectOption[]>([]);
  const [dropdownLoading, setDropdownLoading] = useState(false);

  // ✅ Kept — Worldwide cities (memoized once, deduplicated as "City, CountryCode")
  // Now used only as a fallback for displaying legacy/saved values
  const cityOptions = useMemo<SelectOption[]>(() => {
    try {
      const all = City.getAllCities();
      const seen = new Set<string>();
      const opts: SelectOption[] = [];
      for (const c of all) {
        const label = `${c.name}, ${c.countryCode}`;
        if (seen.has(label)) continue;
        seen.add(label);
        opts.push({ value: c.name, label });
      }
      opts.sort((a, b) => String(a.label).localeCompare(String(b.label)));
      return opts;
    } catch (err) {
      console.warn("Failed to load city dataset:", err);
      return [];
    }
  }, []);

  // ✅ NEW — Live city search via Nominatim (OpenStreetMap)
  // Free, no API key, accurate worldwide city names.
  // Debounced 350ms to respect Nominatim's usage policy (~1 req/sec).
  const cityDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const loadCityOptions = (inputValue: string): Promise<SelectOption[]> => {
    if (cityDebounceRef.current) clearTimeout(cityDebounceRef.current);
    return new Promise((resolve) => {
      const q = inputValue.trim();
      if (q.length < 2) return resolve([]);
      cityDebounceRef.current = setTimeout(async () => {
        try {
          const res = await fetch(
            `https://nominatim.openstreetmap.org/search?city=${encodeURIComponent(
              q,
            )}&format=json&addressdetails=1&limit=10&accept-language=en`,
            { headers: { Accept: "application/json" } },
          );
          if (!res.ok) return resolve([]);
          const data = await res.json();
          const seen = new Set<string>();
          const opts: SelectOption[] = [];
          for (const item of data) {
            const addr = item.address || {};
            const cityName =
              addr.city ||
              addr.town ||
              addr.village ||
              addr.municipality ||
              addr.county ||
              (item.display_name ? item.display_name.split(",")[0] : "");
            if (!cityName) continue;
            const country = addr.country || "";
            const label = country ? `${cityName}, ${country}` : cityName;
            const key = label.toLowerCase();
            if (seen.has(key)) continue;
            seen.add(key);
            opts.push({ value: cityName, label });
          }
          resolve(opts);
        } catch (err) {
          console.warn("City search failed:", err);
          resolve([]);
        }
      }, 350);
    });
  };

  useEffect(() => {
    if (!isOpen) return;
    setDropdownLoading(true);
    Promise.all([
      fetchApi<any[]>(`${COMPANIES_API_BASE_URL}/standards`),
      fetchApi<any[]>(`${COMPANIES_API_BASE_URL}/countries`),
    ])
      .then(([standards, countries]) => {
        setStandardsList(
          (standards ?? []).map((s: any) => ({
            value: Number(s.id),
            label: s.name,
          })),
        );
        setCountriesList(
          (countries ?? []).map((c: any) => ({ value: c.id, label: c.name })),
        );
      })
      .catch(() => toast.error("Failed to load dropdown data"))
      .finally(() => setDropdownLoading(false));
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getCompany(editId)
        .then((c) => {
          setForm({
            name: c.name || "",
            email: c.email || "",
            address: c.address || "",
            city: c.city || "",
            contact_person: c.contact_person || "",
            designation: c.designation || "",
            mobile: c.mobile || "",
            telephone: c.telephone || "",
            fax: c.fax || "",
            validity: c.validity || "",
            certification_body: c.certification_body || "",
            client_group: (c as any).client_group || "",
            accreditation: c.accreditation || "",
            scope_of_work: c.scope_of_work || "",
            reference_number: c.reference_number || "",
            country_id: c.country?.id ?? undefined,
            standard_ids: Array.isArray(c.standards)
              ? c.standards.map((s) => Number(typeof s === "object" ? s.id : s))
              : [],
            documents: Array.isArray((c as any).documents)
              ? (c as any).documents.flat().filter(Boolean)
              : [],
          });
        })
        .catch(() => toast.error("Failed to load company data"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT });
      setErrors({});
      setTouched({});
    }
  }, [isOpen, editId]);

  const handleChange = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const { name, value } = e.target;
    setForm((p) => ({ ...p, [name]: value }));
    setTouched((p) => ({ ...p, [name]: true }));
    setErrors((p) => ({ ...p, [name]: "" }));
  };

  const handleSelectSingle = (name: string, sel: SelectOption | null) => {
    setForm((p) => ({ ...p, [name]: sel?.value ?? undefined }));
    setTouched((p) => ({ ...p, [name]: true }));
    setErrors((p) => ({ ...p, [name]: "" }));
  };

  const handleSelectMulti = (selected: readonly SelectOption[]) => {
    setForm((p) => ({
      ...p,
      standard_ids: selected.map((s) => Number(s.value)),
    }));
  };

  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    if (!files.length) return;
    const uploaded: UploadedDocument[] = files.map((f) => ({
      originalName: f.name,
      fileName: f.name,
      filePath: `uploads/company-documents/${f.name}`,
      rawFile: f,
    }));
    setForm((p) => ({ ...p, documents: [...p.documents, ...uploaded] }));
    if (fileRef.current) fileRef.current.value = "";
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const files = Array.from(e.dataTransfer.files);
    const uploaded: UploadedDocument[] = files.map((f) => ({
      originalName: f.name,
      fileName: f.name,
      filePath: `uploads/company-documents/${f.name}`,
      rawFile: f,
    }));
    setForm((p) => ({ ...p, documents: [...p.documents, ...uploaded] }));
  };

  const removeDoc = (idx: number) =>
    setForm((p) => ({
      ...p,
      documents: p.documents.filter((_, i) => i !== idx),
    }));

  const showErr = (key: string) => !!(errors[key] && touched[key]);

  // ✅ UPDATED — only name, scope_of_work, and standards are required
  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = "Company name is required";
    if (!form.client_group || !String(form.client_group).trim())
      e.client_group = "Client group is required";
    if (!form.scope_of_work.trim())
      e.scope_of_work = "Scope of work is required";
    if (!form.standard_ids.length)
      e.standard_ids = "Select at least one standard";
    setErrors(e);
    setTouched((p) => ({
      ...p,
      ...Object.fromEntries(Object.keys(e).map((k) => [k, true])),
    }));
    return Object.keys(e).length === 0;
  };

  // ── Submit ─────────────────────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setSaving(true);
    try {
      const payload = {
        name: form.name,
        email: form.email,
        address: form.address,
        city: form.city,
        contact_person: form.contact_person,
        designation: form.designation,
        mobile: form.mobile,
        telephone: form.telephone,
        fax: form.fax,
        validity: form.validity,
        certification_body: form.certification_body,
        client_group: form.client_group || "",
        accreditation: form.accreditation,
        scope_of_work: form.scope_of_work,
        reference_number: form.reference_number || "",
        country_id: form.country_id,
        standards: form.standard_ids,
        documents: form.documents,
      };

      if (isEdit && editId) {
        // ✅ CHANGE 3 — edit path unchanged
        await updateCompany(editId, payload);
        toast.success("Company updated successfully");
        onClose();
        refreshData?.();
      } else {
        // ✅ CHANGE 4 — create ONCE, pass result to onSuccess
        const created = await createCompany(payload);
        toast.success("Company created successfully");
        onSuccess?.(created);
        onClose();
        refreshData?.();
      }
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save company.");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  const selCountry =
    countriesList.find((c) => c.value === form.country_id) ?? null;
  const selStandards = standardsList.filter((s) =>
    form.standard_ids.includes(Number(s.value)),
  );
  const selValidity =
    VALIDITY_OPTIONS.find((o) => o.value === form.validity) ?? null;

  // ✅ Resolve selected city (with fallback for legacy free-text values)
  const selCity: SelectOption | null = (() => {
    if (!form.city) return null;
    const match = cityOptions.find(
      (o) => String(o.value).toLowerCase() === form.city.toLowerCase(),
    );
    if (match) return match;
    return { value: form.city, label: form.city };
  })();

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
        {/* ── Header ──────────────────────────────────────────────────── */}
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>
              {isEdit ? "✏️ Edit Company" : "🏢 New Company"}
            </h2>
            <p className={styles.modalSubtitle}>
              {isEdit
                ? "Update company certification details"
                : "Register a new company for ISO certification"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">
            ✕
          </button>
        </div>

        {/* ── Loading ──────────────────────────────────────────────────── */}
        {loadingEdit ? (
          <div className={styles.loadingSpinner}>
            <div className={styles.loadingSpinnerIcon} />
            Loading company data...
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>
              {/* ══ Company Information ═════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />
                Company Information
              </div>
              <div className={styles.grid2}>
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>
                    Company Name <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <input
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    placeholder="e.g. ACME LLC"
                    className={`${styles.input} ${showErr("name") ? styles.inputError : ""}`}
                  />
                  {showErr("name") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>
                      {errors.name}
                    </span>
                  )}
                </div>
                {/* ✅ NEW — Client Group dropdown (REQUIRED) */}
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>
                    Client Group <span style={{ color: "#ef4444" }}>*</span>{" "}
                    <span
                      title="Which internal team handles this client (QRS / TQS / QRS Team A / QRS Team B)"
                      style={{
                        cursor: "help",
                        color: "#94a3b8",
                        fontSize: 12,
                        fontWeight: 400,
                      }}
                    >
                      ⓘ
                    </span>
                  </label>
                  <Select
                    classNamePrefix="rselect"
                    options={CLIENT_GROUP_OPTIONS}
                    value={
                      CLIENT_GROUP_OPTIONS.find(
                        (o) => o.value === form.client_group,
                      ) ?? null
                    }
                    onChange={(s) =>
                      handleSelectSingle(
                        "client_group",
                        s as SelectOption | null,
                      )
                    }
                    isSearchable={false}
                    isClearable
                    placeholder="Select client group..."
                    styles={
                      showErr("client_group")
                        ? {
                            control: (base) => ({
                              ...base,
                              borderColor: "#ef4444",
                              boxShadow: "0 0 0 1px #ef4444",
                              "&:hover": { borderColor: "#ef4444" },
                            }),
                          }
                        : undefined
                    }
                  />
                  {showErr("client_group") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>
                      {errors.client_group}
                    </span>
                  )}
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Validity</label>
                  <Select
                    classNamePrefix="rselect"
                    options={VALIDITY_OPTIONS}
                    value={selValidity}
                    onChange={(s) =>
                      handleSelectSingle("validity", s as SelectOption | null)
                    }
                    isSearchable={false}
                    placeholder="Select validity..."
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Certification Body</label>
                  <input
                    name="certification_body"
                    value={form.certification_body}
                    onChange={handleChange}
                    className={styles.input}
                    placeholder="QRS"
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Accreditation</label>
                  <input
                    name="accreditation"
                    value={form.accreditation}
                    onChange={handleChange}
                    className={styles.input}
                    placeholder="ASCB"
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Reference Number</label>
                  <input
                    name="reference_number"
                    value={form.reference_number ?? ""}
                    onChange={handleChange}
                    className={styles.input}
                    placeholder="ATT/IMS/01"
                  />
                </div>

                <div className={`${styles.formGroup} ${styles.full}`}>
                  {/* ✅ UPDATED — Scope of Work now required */}
                  <label className={styles.label}>
                    Scope of Work <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <textarea
                    name="scope_of_work"
                    value={form.scope_of_work ?? ""}
                    onChange={handleChange}
                    className={`${styles.textarea} ${showErr("scope_of_work") ? styles.inputError : ""}`}
                    rows={3}
                    placeholder="Describe the company's scope of work..."
                  />
                  {showErr("scope_of_work") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>
                      {errors.scope_of_work}
                    </span>
                  )}
                </div>
              </div>

              {/* ══ Location ════════════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />
                Location
              </div>
              <div className={styles.grid2}>
                <div className={`${styles.formGroup} ${styles.full}`}>
                  {/* ✅ UPDATED — Address now optional */}
                  <label className={styles.label}>Address</label>
                  <input
                    name="address"
                    value={form.address}
                    onChange={handleChange}
                    placeholder="P.O.BOX 1234, Street Name"
                    className={styles.input}
                  />
                </div>

                <div className={styles.formGroup}>
                  {/* ✅ UPDATED — City now uses live OpenStreetMap (Nominatim)
                      search for accurate worldwide city names.
                      Free, no API key, debounced 350ms. */}
                  <label className={styles.label}>City</label>
                  <AsyncSelect
                    classNamePrefix="rselect"
                    cacheOptions
                    defaultOptions={false}
                    value={selCity}
                    loadOptions={loadCityOptions}
                    onChange={(s) => {
                      const opt = s as SelectOption | null;
                      setForm((p) => ({
                        ...p,
                        city: opt ? String(opt.value) : "",
                      }));
                      setTouched((p) => ({ ...p, city: true }));
                      setErrors((p) => ({ ...p, city: "" }));
                    }}
                    isClearable
                    placeholder="Type to search city..."
                    noOptionsMessage={({ inputValue }) =>
                      !inputValue || inputValue.length < 2
                        ? "Type at least 2 characters"
                        : "No cities found"
                    }
                  />
                </div>

                <div className={styles.formGroup}>
                  {/* ✅ UPDATED — Country now optional */}
                  <label className={styles.label}>Country</label>
                  <Select
                    classNamePrefix="rselect"
                    options={countriesList}
                    value={selCountry}
                    onChange={(s) =>
                      handleSelectSingle("country_id", s as SelectOption | null)
                    }
                    isLoading={dropdownLoading}
                    isSearchable
                    placeholder="Search country..."
                    noOptionsMessage={() => "No countries found"}
                  />
                </div>
              </div>

              {/* ══ Contact Details ══════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />
                Contact Details
              </div>
              <div className={styles.grid2}>
                <div className={styles.formGroup}>
                  {/* ✅ UPDATED — Contact Person now optional */}
                  <label className={styles.label}>Contact Person</label>
                  <input
                    name="contact_person"
                    value={form.contact_person}
                    onChange={handleChange}
                    placeholder="Mr. John"
                    className={styles.input}
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Designation</label>
                  <input
                    name="designation"
                    value={form.designation ?? ""}
                    onChange={handleChange}
                    className={styles.input}
                    placeholder="Manager"
                  />
                </div>

                <div className={styles.formGroup}>
                  {/* ✅ UPDATED — Email now optional */}
                  <label className={styles.label}>Email</label>
                  <input
                    type="email"
                    name="email"
                    value={form.email}
                    onChange={handleChange}
                    placeholder="contact@company.ae"
                    className={styles.input}
                  />
                </div>

                <div className={styles.formGroup}>
                  {/* ✅ UPDATED — Mobile now optional */}
                  <label className={styles.label}>Mobile</label>
                  <input
                    name="mobile"
                    value={form.mobile}
                    onChange={handleChange}
                    placeholder="0501234567"
                    className={styles.input}
                  />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Telephone</label>
                  <input
                    name="telephone"
                    value={form.telephone ?? ""}
                    onChange={handleChange}
                    className={styles.input}
                    placeholder="0212345678"
                  />
                </div>

                {showField("fax") && (
                  <div className={styles.formGroup}>
                    <label className={styles.label}>Fax</label>
                    <input
                      name="fax"
                      value={form.fax ?? ""}
                      onChange={handleChange}
                      className={styles.input}
                      placeholder="NONE"
                    />
                  </div>
                )}
              </div>

              {/* ══ ISO Standards ════════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />
                ISO Standards{" "}
                <span
                  style={{
                    color: "#ef4444",
                    fontWeight: 400,
                    textTransform: "none",
                  }}
                >
                  *
                </span>
              </div>
              <Select
                classNamePrefix="rselect"
                isMulti
                options={standardsList}
                value={selStandards}
                onChange={handleSelectMulti}
                isLoading={dropdownLoading}
                placeholder="Search and select standards..."
                noOptionsMessage={() => "No standards found"}
                closeMenuOnSelect={false}
              />
              {showErr("standard_ids") && (
                <span
                  className={`${styles.error} ${styles.errorAnimate}`}
                  style={{ marginTop: 4 }}
                >
                  {errors.standard_ids}
                </span>
              )}
              {/* ══ Documents ════════════════════════════════════════════ */}
              {/* ══ Documents ════════════════════════════════════════════ */}
              {showField("documents") && (
                <>
                  <div className={styles.sectionHeader}>
                    <span className={styles.sectionDot} />
                    Intercom Documents (PDF / Word)
                  </div>
                  <div
                    className={styles.fileUploadZone}
                    onClick={() => fileRef.current?.click()}
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={handleDrop}
                  >
                    <input
                      ref={fileRef}
                      type="file"
                      multiple
                      accept=".pdf,.doc,.docx"
                      className={styles.fileHiddenInput}
                      onChange={handleFileChange}
                    />
                    <div className={styles.fileUploadIcon}>📤</div>
                    <div className={styles.fileUploadText}>
                      Click to upload or drag and drop
                    </div>
                    <div className={styles.fileUploadHint}>
                      PDF, DOC, DOCX files accepted
                    </div>
                  </div>

                  {form.documents.length > 0 && (
                    <div className={styles.fileList}>
                      {form.documents.map((doc, idx) => (
                        <div key={idx} className={styles.fileItem}>
                          <div className={styles.fileItemName}>
                            <span>📄</span>
                            <span>{doc.originalName || doc.fileName}</span>
                          </div>
                          <button
                            type="button"
                            className={styles.fileRemoveBtn}
                            onClick={() => removeDoc(idx)}
                          >
                            Remove
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </>
              )}
            </div>

            {/* ── Footer ────────────────────────────────────────────── */}
            <div className={styles.modalFooter}>
              <button
                type="button"
                onClick={onClose}
                className={styles.cancelBtn}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className={styles.saveBtn}
              >
                {saving
                  ? isEdit
                    ? "Updating…"
                    : "Saving..."
                  : isEdit
                    ? "Update Company"
                    : "Save"}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}