"use client";

import React, { useEffect, useState, ChangeEvent } from "react";
import Select from "react-select";
import AsyncSelect from "react-select/async";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { createJob, updateJob, getJob } from "@/lib/api/job.api";
import { useJobDropdowns } from "../hooks/useJobDropdowns";
import type {
  CreateJobDto,
  JobStage,
  MdRisk,
  ScheduleSlot,
  SelectOption,
} from "@/lib/api/types/job.types";

// ─── Static options ───────────────────────────────────────────────────────────
const STAGE_OPTIONS: SelectOption[]    = [{ value: "Stage 1", label: "Stage 1" }, { value: "Stage 2", label: "Stage 2" }];
const RISK_OPTIONS: SelectOption[]     = [{ value: "Low", label: "🟢 Low" }, { value: "Medium", label: "🟡 Medium" }, { value: "High", label: "🔴 High" }];
const SCHEDULE_OPTIONS: SelectOption[] = [{ value: "MORNING", label: "🌅 Morning" }, { value: "AFTERNOON", label: "🌇 Afternoon" }, { value: "FULL_DAY", label: "📅 Full Day" }];
const MD_OPTIONS: SelectOption[]       = [".5", "1", "1.5", "2", "2.5", "3"].map((v) => ({ value: v, label: v }));

// ─── Props ────────────────────────────────────────────────────────────────────
interface JobFormProps {
  isOpen:       boolean;
  onClose:      () => void;
  refreshData?: () => void;
  editId?:      number | null;
}

// ─── Default form state ───────────────────────────────────────────────────────
const DEFAULT = {
  company_id:    0,
  template_id:   0,
  auditStageId:  0,
  stage:         "Stage 1" as JobStage,
  standard_ids:  [] as number[],
  leadAuditorId: 0,
  date:          "",
  docReview:     "",
  numEmployees:  0,
  naceEacCodes:  "",
  md:            ".5",
  mdRisk:        "Medium"  as MdRisk,
  scheduleSlot:  "MORNING" as ScheduleSlot,
  prepareDate:   "",
  approvedDate:  "",
};

// ─── Component ────────────────────────────────────────────────────────────────
export default function JobForm({ isOpen, onClose, refreshData, editId }: JobFormProps) {
  const isEdit = Boolean(editId);

  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);

  // Selected company option kept separately (AsyncSelect needs the full object)
  const [selectedCompany, setSelectedCompany] = useState<SelectOption | null>(null);

  // Load all static dropdowns from the hook
  const {
    standardOptions,
    templateOptions,
    auditStageOptions,
    auditorOptions,
    loading: dropdownLoading,
    loadCompanyOptions,
  } = useJobDropdowns();

  // ── Hydrate on edit ───────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getJob(editId)
        .then((j) => {
          setForm({
            company_id:    j.company?.id        ?? 0,
            template_id:   j.template?.id       ?? 0,
            auditStageId:  j.auditStageId       ?? 0,
            stage:         j.stage              ?? "Stage 1",
            standard_ids:  j.standards?.map((s) => s.id) ?? [],
            leadAuditorId: j.leadAuditor?.id    ?? 0,
            date:          j.date?.substring(0, 10)       ?? "",
            docReview:     j.docReview?.substring(0, 10)  ?? "",
            numEmployees:  j.numEmployees        ?? 0,
            naceEacCodes:  j.naceEacCodes        ?? "",
            md:            j.md                 ?? ".5",
            mdRisk:        j.mdRisk             ?? "Medium",
            scheduleSlot:  j.scheduleSlot       ?? "MORNING",
            prepareDate:   j.prepareDate  ? j.prepareDate.substring(0, 10)  : "",
            approvedDate:  j.approvedDate ? j.approvedDate.substring(0, 10) : "",
          });
          // Restore company label for AsyncSelect
          if (j.company) {
            setSelectedCompany({ value: j.company.id, label: j.company.name });
          }
        })
        .catch(() => toast.error("Failed to load job data"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT });
      setSelectedCompany(null);
      setErrors({});
      setTouched({});
    }
  }, [isOpen, editId]);

  // ── Field handlers ────────────────────────────────────────────────────────
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setForm((p) => ({ ...p, [name]: name === "numEmployees" ? Number(value) : value }));
    setTouched((p) => ({ ...p, [name]: true }));
    setErrors((p) => ({ ...p, [name]: "" }));
  };

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

  const handleCompanyChange = (opt: SelectOption | null) => {
    setSelectedCompany(opt);
    setForm((p) => ({ ...p, company_id: opt ? Number(opt.value) : 0 }));
    setTouched((p) => ({ ...p, company_id: true }));
    setErrors((p) => ({ ...p, company_id: "" }));
  };

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

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

  // ── Validation ────────────────────────────────────────────────────────────
  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.company_id)          e.company_id    = "Company is required";
    if (!form.template_id)         e.template_id   = "Template is required";
    if (!form.leadAuditorId)       e.leadAuditorId = "Lead auditor is required";
    if (!form.date)                e.date          = "Audit date 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: CreateJobDto = {
        company_id:    form.company_id,
        template_id:   form.template_id,
        stage:         form.stage,
        standard_ids:  form.standard_ids,
        leadAuditorId: form.leadAuditorId,
        date:          form.date,
        docReview:     form.docReview || form.date,
        numEmployees:  form.numEmployees,
        naceEacCodes:  form.naceEacCodes,
        md:            form.md,
        mdRisk:        form.mdRisk,
        scheduleSlot:  form.scheduleSlot,
        ...(form.auditStageId  ? { auditStageId:  form.auditStageId }  : {}),
        ...(form.prepareDate   ? { prepareDate:   form.prepareDate }   : {}),
        ...(form.approvedDate  ? { approvedDate:  form.approvedDate }  : {}),
      };
      if (isEdit && editId) {
        await updateJob(editId, payload);
        toast.success("Job updated successfully");
      } else {
        await createJob(payload);
        toast.success("Job created successfully");
      }
      onClose();
      refreshData?.();
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save job.");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  // Derived select values for regular selects
  const selTemplate   = templateOptions.find((o)   => o.value === form.template_id)   ?? null;
  const selAuditStage = auditStageOptions.find((o) => o.value === form.auditStageId)  ?? null;
  const selAuditor    = auditorOptions.find((o)    => o.value === form.leadAuditorId) ?? null;
  const selStage      = STAGE_OPTIONS.find((o)     => o.value === form.stage)         ?? null;
  const selRisk       = RISK_OPTIONS.find((o)      => o.value === form.mdRisk)        ?? null;
  const selSchedule   = SCHEDULE_OPTIONS.find((o)  => o.value === form.scheduleSlot) ?? null;
  const selMd         = MD_OPTIONS.find((o)        => o.value === form.md)            ?? null;
  const selStandards  = standardOptions.filter((s) => form.standard_ids.includes(Number(s.value)));

  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 Job" : "📋 New Job"}</h2>
            <p className={styles.modalSubtitle}>
              {isEdit ? "Update job registration details" : "Register a new audit job"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">✕</button>
        </div>

        {/* ── Loading spinner ───────────────────────────────────────── */}
        {loadingEdit ? (
          <div className={styles.loadingSpinner}>
            <div className={styles.loadingSpinnerIcon} />
            Loading job data...
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>

              {/* ══ Company & Stage ══════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />Job Information
              </div>
              <div className={styles.grid2}>

                {/* Company — AsyncSelect (search-as-you-type, 7442 records) */}
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>
                    Company <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <AsyncSelect
                    classNamePrefix="rselect"
                    cacheOptions
                    defaultOptions
                    loadOptions={loadCompanyOptions}
                    value={selectedCompany}
                    onChange={handleCompanyChange}
                    placeholder="Type to search company..."
                    noOptionsMessage={({ inputValue }) =>
                      inputValue ? "No companies found" : "Type to search..."
                    }
                    loadingMessage={() => "Searching companies..."}
                  />
                  {showErr("company_id") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.company_id}</span>
                  )}
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Stage <span style={{ color: "#ef4444" }}>*</span></label>
                  <Select classNamePrefix="rselect" options={STAGE_OPTIONS} value={selStage}
                    onChange={(s) => handleSelect("stage", s)} isSearchable={false} />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Audit Stage</label>
                  <Select classNamePrefix="rselect" options={auditStageOptions} value={selAuditStage}
                    onChange={(s) => handleSelect("auditStageId", s)}
                    isLoading={dropdownLoading} placeholder="Select audit stage..." />
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Template <span style={{ color: "#ef4444" }}>*</span></label>
                  <Select classNamePrefix="rselect" options={templateOptions} value={selTemplate}
                    onChange={(s) => handleSelect("template_id", s)}
                    isLoading={dropdownLoading} isSearchable placeholder="Search template..." />
                  {showErr("template_id") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.template_id}</span>
                  )}
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Lead Auditor <span style={{ color: "#ef4444" }}>*</span></label>
                  <Select classNamePrefix="rselect" options={auditorOptions} value={selAuditor}
                    onChange={(s) => handleSelect("leadAuditorId", s)}
                    isLoading={dropdownLoading} isSearchable placeholder="Search auditor..." />
                  {showErr("leadAuditorId") && (
                    <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.leadAuditorId}</span>
                  )}
                </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={standardOptions}
                value={selStandards}
                onChange={handleMultiStandards}
                isLoading={dropdownLoading}
                placeholder="Search and select standards..."
                closeMenuOnSelect={false}
              />
              {showErr("standard_ids") && (
                <span className={`${styles.error} ${styles.errorAnimate}`} style={{ marginTop: 4 }}>
                  {errors.standard_ids}
                </span>
              )}

              {/* ══ Dates & Schedule ════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />Dates & Schedule
              </div>
              <div className={styles.grid2}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Audit Date <span style={{ color: "#ef4444" }}>*</span></label>
                  <input type="date" name="date" value={form.date} onChange={handleChange}
                    className={`${styles.input} ${showErr("date") ? styles.inputError : ""}`} />
                  {showErr("date") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.date}</span>}
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Document Review Date</label>
                  <input type="date" name="docReview" value={form.docReview} onChange={handleChange} className={styles.input} />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Prepare Date</label>
                  <input type="date" name="prepareDate" value={form.prepareDate} onChange={handleChange} className={styles.input} />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Approved Date</label>
                  <input type="date" name="approvedDate" value={form.approvedDate} onChange={handleChange} className={styles.input} />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Schedule Slot</label>
                  <Select classNamePrefix="rselect" options={SCHEDULE_OPTIONS} value={selSchedule}
                    onChange={(s) => handleSelect("scheduleSlot", s)} isSearchable={false} />
                </div>
              </div>

              {/* ══ Audit Details ════════════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />Audit Details
              </div>
              <div className={styles.grid2}>
                <div className={styles.formGroup}>
                  <label className={styles.label}>Number of Employees</label>
                  <input type="number" name="numEmployees" value={form.numEmployees}
                    onChange={handleChange} className={styles.input} min={0} />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>NACE / EAC Codes</label>
                  <input name="naceEacCodes" value={form.naceEacCodes} onChange={handleChange}
                    className={styles.input} placeholder="e.g. 25.11/17" />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>MD</label>
                  <Select classNamePrefix="rselect" options={MD_OPTIONS} value={selMd}
                    onChange={(s) => handleSelect("md", s)} isSearchable={false} />
                </div>
                <div className={styles.formGroup}>
                  <label className={styles.label}>MD Risk</label>
                  <Select classNamePrefix="rselect" options={RISK_OPTIONS} value={selRisk}
                    onChange={(s) => handleSelect("mdRisk", s)} isSearchable={false} />
                </div>
              </div>

            </div>{/* /formBody */}

            {/* ── 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 Job" : "Create Job")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
