"use client";

import React, { useState } from "react";
import toast from "react-hot-toast";
import {
  FiPlus,
  FiX,
  FiCheckSquare,
  FiSave,
  FiArrowLeft,
} from "react-icons/fi";
import styles from "../commonstyle/dattabale.module.css";
import {
  createChecklistTemplate,
  updateChecklistTemplate,
} from "@/lib/api/checklist.api";
import type {
  ChecklistTemplate,
  Standard,
} from "@/lib/api/types/checklist.types";

interface TemplateItemDraft {
  id?: number;
  item_text: string;
}

interface Props {
  /** null → creating a new template */
  editing: ChecklistTemplate | null;
  standards: Standard[];
  onBack: () => void;
  onSaved: () => void;
}

// Shared label style — same typography as the table headers (thStyle)
const labelStyle: React.CSSProperties = {
  fontSize: 11,
  fontWeight: 700,
  color: "#6b7280",
  textTransform: "uppercase",
  letterSpacing: "0.05em",
  display: "block",
  marginBottom: 6,
};

export default function ChecklistTemplateEditor({
  editing,
  standards,
  onBack,
  onSaved,
}: Props) {
  const [formName, setFormName] = useState(editing?.name ?? "");
  const [formIsGeneric, setFormIsGeneric] = useState(
    editing ? editing.is_generic : true,
  );
  // Multi-standard support: array of selected standard IDs
  const [formStandardIds, setFormStandardIds] = useState<number[]>(
    editing
      ? (editing as any).standard_ids?.length
        ? (editing as any).standard_ids
        : editing.standard_id
          ? [editing.standard_id]
          : []
      : [],
  );
  const [formItems, setFormItems] = useState<TemplateItemDraft[]>(
    editing
      ? editing.items.map((i) => ({ id: i.id, item_text: i.item_text }))
      : [],
  );
  const [newItemText, setNewItemText] = useState("");
  const [saving, setSaving] = useState(false);

  const toggleStandard = (id: number) => {
    setFormStandardIds((prev) =>
      prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id],
    );
  };

  const addItem = () => {
    if (!newItemText.trim()) return;
    setFormItems((prev) => [...prev, { item_text: newItemText.trim() }]);
    setNewItemText("");
  };

  const removeItem = (index: number) => {
    setFormItems((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSave = async () => {
    if (!formName.trim()) {
      toast.error("Enter a template name");
      return;
    }
    if (!formIsGeneric && formStandardIds.length === 0) {
      toast.error("Select at least one standard, or mark this template as generic");
      return;
    }
    if (formItems.length === 0) {
      toast.error("Add at least one item");
      return;
    }

    setSaving(true);
    try {
      const payload = {
        name: formName.trim(),
        is_generic: formIsGeneric,
        standard_id: formIsGeneric ? null : (formStandardIds[0] ?? null),
        standard_ids: formIsGeneric ? null : formStandardIds,
        items: formItems.map((i, idx) => ({
          item_text: i.item_text,
          sort_order: idx,
        })),
      };

      if (editing) {
        await updateChecklistTemplate(editing.id, payload);
        toast.success(`✅ Template "${payload.name}" updated`);
      } else {
        await createChecklistTemplate(payload);
        toast.success(`✅ Template "${payload.name}" created`);
      }
      onSaved();
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : "Failed to save template",
      );
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className={styles.container}>
      <button
        onClick={onBack}
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          padding: "8px 14px",
          borderRadius: 8,
          border: "1px solid #cbd5e1",
          background: "#fff",
          color: "#475569",
          fontSize: 13,
          fontWeight: 600,
          cursor: "pointer",
          marginBottom: 16,
        }}
      >
        <FiArrowLeft size={14} /> Back to templates
      </button>

      {/* Purple gradient header — same styles.header as the list view */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>
            {editing ? "Edit Template" : "New Checklist Template"}
          </h1>
          <p className={styles.subtitle}>
            Build the list of documents this template requires
          </p>
        </div>
      </div>

      <div className={styles.tableWrapper} style={{ padding: 22 }}>
        <label style={labelStyle}>Template Name</label>
        <input
          type="text"
          value={formName}
          onChange={(e) => setFormName(e.target.value)}
          placeholder="e.g. ISO 45001 — OH&S Specific"
          style={{
            width: "100%",
            padding: "10px 14px",
            border: "1px solid #cbd5e1",
            borderRadius: 8,
            fontSize: 14,
            marginBottom: 18,
            outline: "none",
          }}
        />

        <label style={labelStyle}>Applies To</label>
        <div style={{ display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
          {/* Segmented pills — same active treatment as the filter selects */}
          <button
            type="button"
            onClick={() => setFormIsGeneric(true)}
            style={{
              padding: "7px 14px",
              borderRadius: 8,
              border: formIsGeneric ? "1.5px solid #0f766e" : "1px solid #cbd5e1",
              background: formIsGeneric ? "#f0fdfa" : "#fff",
              color: formIsGeneric ? "#0f766e" : "#475569",
              fontSize: 13,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            🌐 Generic — every audit
          </button>
          <button
            type="button"
            onClick={() => setFormIsGeneric(false)}
            style={{
              padding: "7px 14px",
              borderRadius: 8,
              border: !formIsGeneric ? "1.5px solid #7c3aed" : "1px solid #cbd5e1",
              background: !formIsGeneric ? "#f5f3ff" : "#fff",
              color: !formIsGeneric ? "#7c3aed" : "#475569",
              fontSize: 13,
              fontWeight: 600,
              cursor: "pointer",
            }}
          >
            🎯 Specific to standard(s)
          </button>
        </div>

        {!formIsGeneric && (
          <>
            <label style={labelStyle}>Standards (select one or more)</label>
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 6,
                marginBottom: 18,
                maxHeight: 220,
                overflowY: "auto",
                border: "1px solid #cbd5e1",
                borderRadius: 8,
                padding: 8,
                background: "#fdfcff",
              }}
            >
              {standards.map((s) => {
                const checked = formStandardIds.includes(s.id);
                return (
                  <label
                    key={s.id}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 10,
                      padding: "8px 12px",
                      borderRadius: 8,
                      background: checked ? "#f5f3ff" : "transparent",
                      border: checked ? "1.5px solid #7c3aed" : "1.5px solid transparent",
                      cursor: "pointer",
                      transition: "all 0.12s",
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => toggleStandard(s.id)}
                      style={{ accentColor: "#7c3aed", width: 16, height: 16 }}
                    />
                    <span style={{ fontSize: 13.5, fontWeight: checked ? 700 : 500, color: checked ? "#4a0080" : "#374151" }}>
                      {s.name}
                    </span>
                  </label>
                );
              })}
            </div>
            {formStandardIds.length > 0 && (
              <div style={{ fontSize: 12, color: "#7c3aed", fontWeight: 600, marginBottom: 14, marginTop: -10 }}>
                {formStandardIds.length} standard{formStandardIds.length > 1 ? "s" : ""} selected
              </div>
            )}
          </>
        )}

        <label style={{ ...labelStyle, marginTop: 8 }}>
          Checklist Items ({formItems.length})
        </label>

        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 8,
            marginBottom: 14,
          }}
        >
          {formItems.map((item, idx) => (
            <div
              key={idx}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 10,
                background: "#f8fafc",
                border: "1px solid #f1f5f9",
                borderRadius: 8,
                padding: "10px 14px",
              }}
            >
              <FiCheckSquare size={14} color="#0f766e" />
              <span style={{ flex: 1, fontSize: 13.5, color: "#1e293b" }}>
                {item.item_text}
              </span>
              <button
                onClick={() => removeItem(idx)}
                title="Remove item"
                style={{
                  border: "none",
                  background: "transparent",
                  color: "#dc2626",
                  cursor: "pointer",
                  display: "flex",
                }}
              >
                <FiX size={15} />
              </button>
            </div>
          ))}
          {formItems.length === 0 && (
            <div
              style={{
                textAlign: "center",
                padding: 20,
                color: "#94a3b8",
                fontSize: 13,
              }}
            >
              No items yet — add one below
            </div>
          )}
        </div>

        <div style={{ display: "flex", gap: 10 }}>
          <input
            type="text"
            value={newItemText}
            onChange={(e) => setNewItemText(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && addItem()}
            placeholder="e.g. PPE issuance and inspection records"
            style={{
              flex: 1,
              padding: "10px 14px",
              border: "1px solid #cbd5e1",
              borderRadius: 8,
              fontSize: 13.5,
              outline: "none",
            }}
          />
          <button
            onClick={addItem}
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              padding: "10px 16px",
              background: "#eef2ff",
              color: "#4338ca",
              border: "1px solid #c7d2fe",
              borderRadius: 8,
              fontSize: 13,
              fontWeight: 700,
              cursor: "pointer",
              whiteSpace: "nowrap",
            }}
          >
            <FiPlus size={14} /> Add Item
          </button>
        </div>

        <button
          onClick={handleSave}
          disabled={saving}
          style={{
            width: "100%",
            marginTop: 24,
            padding: 13,
            border: "none",
            borderRadius: 8,
            background: "linear-gradient(135deg, #6a0dad 0%, #4a0080 100%)",
            color: "#fff",
            fontSize: 14,
            fontWeight: 700,
            cursor: saving ? "not-allowed" : "pointer",
            opacity: saving ? 0.7 : 1,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
            boxShadow: "0 2px 8px rgba(74,0,128,0.3)",
          }}
        >
          <FiSave size={15} />{" "}
          {saving ? "Saving..." : editing ? "Save Changes" : "Create Template"}
        </button>
      </div>
    </div>
  );
}