"use client";

import React, { useEffect, useState, ChangeEvent } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { createTemplate, updateTemplate, getTemplate, TEMPLATES_API_BASE_URL } from "@/lib/api/template.api";
import type { CreateTemplateDto, TemplateStage, TemplateType } from "@/lib/api/types/template.types";

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

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

// ─── Options ──────────────────────────────────────────────────────────────────
const STAGE_OPTIONS: SelectOption[] = [
  { value: "Stage 1", label: "Stage 1" },
  { value: "Stage 2", label: "Stage 2" },
];

const TYPE_OPTIONS: SelectOption[] = [
  { value: "DOCUMENT",    label: "📄 DOCUMENT"    },
  { value: "CERTIFICATE", label: "🏆 CERTIFICATE" },
];

const VERSION_OPTIONS: SelectOption[] = [
  { value: "v1.0", label: "v1.0" },
  { value: "v1.1", label: "v1.1" },
  { value: "v1.2", label: "v1.2" },
  { value: "v2.0", label: "v2.0" },
];

// ─── Default state ────────────────────────────────────────────────────────────
const DEFAULT = {
  name:         "",
  stageName:    "Stage 1" as TemplateStage,
  templateType: "DOCUMENT" as TemplateType,
  version:      "v1.0",
  filePath:     "",
  isActive:     true,
};

// ─── Component ────────────────────────────────────────────────────────────────
export default function TemplateForm({ isOpen, onClose, refreshData, editId }: TemplateFormProps) {
  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);

  // ── Hydrate on edit ───────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getTemplate(editId)
        .then((t) => {
          setForm({
            name:         t.name         || "",
            stageName:    t.stageName    || "Stage 1",
            templateType: t.templateType || "DOCUMENT",
            version:      t.version      || "v1.0",
            filePath:     t.filePath     || "",
            isActive:     t.isActive     ?? true,
          });
        })
        .catch(() => toast.error("Failed to load template data"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT });
      setErrors({});
      setTouched({});
    }
  }, [isOpen, editId]);

  // ── Field handlers ────────────────────────────────────────────────────────
  const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target as HTMLInputElement;
    const val = type === "checkbox" ? (e.target as HTMLInputElement).checked : value;
    setForm((p) => ({ ...p, [name]: val }));
    setTouched((p) => ({ ...p, [name]: true }));
    setErrors((p) => ({ ...p, [name]: "" }));
  };

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

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

  // ── Validation ────────────────────────────────────────────────────────────
  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.name.trim())     e.name     = "Template name is required";
    if (!form.filePath.trim()) e.filePath = "File path is required";
    if (!form.stageName)       e.stageName    = "Stage is required";
    if (!form.templateType)    e.templateType = "Type is required";
    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: CreateTemplateDto = {
        name:         form.name.trim(),
        stageName:    form.stageName,
        templateType: form.templateType,
        version:      form.version || "v1.0",
        filePath:     form.filePath.trim(),
        isActive:     form.isActive,
      };
      if (isEdit && editId) {
        await updateTemplate(editId, payload);
        toast.success("Template updated successfully");
      } else {
        await createTemplate(payload);
        toast.success("Template created successfully");
      }
      onClose();
      refreshData?.();
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save template.");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  // Derived select values
  const selStage   = STAGE_OPTIONS.find((o) => o.value === form.stageName)   ?? null;
  const selType    = TYPE_OPTIONS.find((o)  => o.value === form.templateType) ?? null;
  const selVersion = VERSION_OPTIONS.find((o) => o.value === form.version)   ?? null;

  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 Template" : "📄 New Template"}
            </h2>
            <p className={styles.modalSubtitle}>
              {isEdit ? "Update template details" : "Register a new PDF document or certificate template"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">✕</button>
        </div>

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

              {/* ══ Template Information ════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />Template Information
              </div>
              <div className={styles.grid2}>

                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>Template Name <span style={{ color: "#ef4444" }}>*</span></label>
                  <input
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    placeholder="e.g. Form 04-5 STAGE 1 AUDIT PLAN QMS-9001"
                    className={`${styles.input} ${showErr("name") ? styles.inputError : ""}`}
                  />
                  {showErr("name") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.name}</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) => handleSelectSingle("stageName", s as SelectOption | null)}
                    isSearchable={false}
                    placeholder="Select stage..."
                  />
                  {showErr("stageName") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.stageName}</span>}
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Template Type <span style={{ color: "#ef4444" }}>*</span></label>
                  <Select
                    classNamePrefix="rselect"
                    options={TYPE_OPTIONS}
                    value={selType}
                    onChange={(s) => handleSelectSingle("templateType", s as SelectOption | null)}
                    isSearchable={false}
                    placeholder="Select type..."
                  />
                  {showErr("templateType") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.templateType}</span>}
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Version</label>
                  <Select
                    classNamePrefix="rselect"
                    options={VERSION_OPTIONS}
                    value={selVersion}
                    onChange={(s) => handleSelectSingle("version", s as SelectOption | null)}
                    isSearchable={false}
                    placeholder="Select version..."
                  />
                </div>

              </div>

              {/* ══ File Configuration ══════════════════════════════════ */}
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />File Configuration
              </div>
              <div className={styles.grid2}>

                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>File Path (slug) <span style={{ color: "#ef4444" }}>*</span></label>
                  <input
                    name="filePath"
                    value={form.filePath}
                    onChange={handleChange}
                    placeholder="e.g. form-04-5-stage-1-audit-plan-qms-9001"
                    className={`${styles.input} ${showErr("filePath") ? styles.inputError : ""}`}
                  />
                  {showErr("filePath") && <span className={`${styles.error} ${styles.errorAnimate}`}>{errors.filePath}</span>}
                  <span style={{ fontSize: "11px", color: "#6b7280", marginTop: "3px", display: "block" }}>
                    Used in PDF URL: /api/pdf/{form.stageName?.toLowerCase().replace(" ", "") || "stage1"}/<strong>{form.filePath || "..."}</strong>
                  </span>
                </div>

                <div className={styles.formGroup}>
                  <label className={styles.label}>Active Status</label>
                  <label style={{ display: "flex", alignItems: "center", gap: "10px", fontSize: "14px", color: "#374151", cursor: "pointer", marginTop: "8px" }}>
                    <input
                      type="checkbox"
                      name="isActive"
                      checked={form.isActive}
                      onChange={handleChange}
                      style={{ width: "16px", height: "16px", accentColor: "#14b8a6", cursor: "pointer" }}
                    />
                    Active (visible in dropdowns and lists)
                  </label>
                </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 Template" : "Save Template")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
