"use client";

import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import styles from "./../../commonstyle/FormStyles.module.css";
import {
  createAuditStage,
  updateAuditStage,
  getAuditStage,
} from "@/lib/api/auditStage.api";
import type { CreateAuditStageDto } from "@/lib/api/types/auditStage.types";

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

const DEFAULT = { name: "", description: "", order: "" as string | number };

export default function AuditStageForm({ isOpen, onClose, refreshData, editId }: Props) {
  const isEdit = Boolean(editId);

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

  // ── Hydrate on edit ──────────────────────────────────────────────────────
  useEffect(() => {
    if (!isOpen) return;
    if (editId) {
      setLoadingEdit(true);
      getAuditStage(editId)
        .then((s) => {
          setForm({
            name:        s.name        || "",
            description: s.description || "",
            order:       s.order       ?? "",
          });
        })
        .catch(() => toast.error("Failed to load stage data"))
        .finally(() => setLoadingEdit(false));
    } else {
      setForm({ ...DEFAULT });
      setErrors({});
    }
  }, [isOpen, editId]);

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = "Stage name is required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setSaving(true);
    try {
      const payload: CreateAuditStageDto = {
        name:        form.name.trim(),
        description: form.description.trim() || undefined,
        order:       form.order !== "" ? Number(form.order) : undefined,
      };
      if (isEdit && editId) {
        await updateAuditStage(editId, payload);
        toast.success("Audit stage updated successfully");
      } else {
        await createAuditStage(payload);
        toast.success("Audit stage created successfully");
      }
      onClose();
      refreshData?.();
    } catch (err: any) {
      toast.error(err?.message ?? "Failed to save audit stage");
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        style={{ maxWidth: 560 }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* ── Header ────────────────────────────────────────────────────── */}
        <div
          className={styles.modalHeader}
          style={{ background: "linear-gradient(135deg, #4c1d95 0%, #7c3aed 100%)" }}
        >
          <div>
            <h2 className={styles.modalTitle} style={{ color: "#fff" }}>
              {isEdit ? "✏️ Edit Audit Stage" : "⚙️ New Audit Stage"}
            </h2>
            <p className={styles.modalSubtitle} style={{ color: "#ddd6fe", margin: 0, fontSize: 13 }}>
              {isEdit ? "Update stage configuration" : "Add a new stage type to the lookup list"}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button" style={{ color: "#fff" }}>✕</button>
        </div>

        {/* ── Body ──────────────────────────────────────────────────────── */}
        {loadingEdit ? (
          <div className={styles.loadingSpinner} style={{ padding: 40 }}>
            <div className={styles.loadingSpinnerIcon} />
            Loading stage data...
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={styles.form}>
            <div className={styles.formBody}>
              <div className={styles.sectionHeader}>
                <span className={styles.sectionDot} />Stage Configuration
              </div>

              <div className={styles.grid2}>
                {/* Name */}
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>
                    Stage Name <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <input
                    name="name"
                    value={form.name}
                    onChange={(e) => { setForm((p) => ({ ...p, name: e.target.value })); setErrors((p) => ({ ...p, name: "" })); }}
                    placeholder="e.g. Stage 1, Surveillance, Recertification"
                    className={`${styles.input} ${errors.name ? styles.inputError : ""}`}
                  />
                  {errors.name && <span className={styles.error}>{errors.name}</span>}
                </div>

                {/* Sort Order */}
                <div className={styles.formGroup}>
                  <label className={styles.label}>Sort Order</label>
                  <input
                    type="number"
                    min={1}
                    value={form.order}
                    onChange={(e) => setForm((p) => ({ ...p, order: e.target.value }))}
                    placeholder="1, 2, 3..."
                    className={styles.input}
                  />
                </div>

                {/* Description */}
                <div className={`${styles.formGroup} ${styles.full}`}>
                  <label className={styles.label}>Description</label>
                  <textarea
                    value={form.description}
                    onChange={(e) => setForm((p) => ({ ...p, description: e.target.value }))}
                    className={styles.textarea}
                    rows={3}
                    placeholder="Brief description of this audit stage..."
                  />
                </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}
                style={{ background: "#7c3aed" }}
              >
                {saving
                  ? (isEdit ? "Updating..." : "Creating...")
                  : (isEdit ? "Update Stage" : "Create Stage")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
