import { useState, useCallback } from "react";

// ─── CONFIG ────────────────────────────────────────────────────────────────
const MONTHS = [
  { key: "april", label: "April" },
  { key: "may", label: "May" },
  { key: "june", label: "June" },
  { key: "july", label: "July" },
  { key: "august", label: "August" },
  { key: "september", label: "September" },
  { key: "october", label: "October" },
  { key: "november", label: "November" },
  { key: "december", label: "December" },
  { key: "january", label: "January" },
  { key: "february", label: "February" },
  { key: "march", label: "March" },
];

const CURRENCY = "₹";

const defaultRow = () => ({
  due_date: "",
  fine_type: "", // "" | "percentage" | "fix"
  percentage: "",
  fine_amount: "",
});

// ─── STYLES ────────────────────────────────────────────────────────────────
const css = `
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=DM+Mono:wght@400;500&display=swap');

  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  .tfm-root {
    font-family: 'Inter', sans-serif;
    background: #f0f4ff;
    color: #1e2a4a;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }

  /* NAV */
  .tfm-nav {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 28px; height: 60px;
    background: #1a56db;
    border-bottom: 1px solid #1648c4;
    position: sticky; top: 0; z-index: 50;
  }
  .tfm-nav-brand { display: flex; align-items: center; gap: 10px; }
  .tfm-nav-logo {
    width: 34px; height: 34px; border-radius: 8px;
    background: rgba(255,255,255,0.2);
    display: grid; place-items: center; font-size: 16px;
  }
  .tfm-nav-name { font-size: 16px; font-weight: 700; letter-spacing: -.3px; color: #fff; }
  .tfm-nav-name span { color: #bfdbfe; }
  .tfm-nav-right { display: flex; align-items: center; gap: 12px; }
  .tfm-nav-chip {
    font-size: 11px; color: #bfdbfe;
    background: rgba(255,255,255,0.15);
    border: 1px solid rgba(255,255,255,0.2);
    padding: 3px 10px; border-radius: 20px;
  }
  .tfm-avatar {
    width: 32px; height: 32px; border-radius: 50%;
    background: rgba(255,255,255,0.25);
    display: grid; place-items: center;
    font-size: 13px; font-weight: 700; cursor: pointer; color: #fff;
  }

  /* LAYOUT */
  .tfm-body { display: flex; flex: 1; }

  /* SIDEBAR */
  .tfm-aside {
    width: 215px; flex-shrink: 0;
    background: #fff;
    border-right: 1px solid #e2e8f8;
    padding: 16px 10px;
    display: flex; flex-direction: column; gap: 2px;
  }
  .tfm-aside-sec {
    font-size: 9.5px; letter-spacing: .14em; text-transform: uppercase;
    color: #94a3b8; padding: 12px 10px 5px;
  }
  .tfm-aside-item {
    display: flex; align-items: center; gap: 9px;
    padding: 8px 11px; border-radius: 9px;
    font-size: 13px; color: #64748b;
    cursor: pointer; transition: all .15s;
  }
  .tfm-aside-item:hover { background: #eff6ff; color: #1a56db; }
  .tfm-aside-item.active { background: #dbeafe; color: #1a56db; font-weight: 600; }
  .tfm-aside-icon { font-size: 15px; width: 18px; text-align: center; }

  /* MAIN */
  .tfm-main { flex: 1; padding: 28px 32px; overflow-x: hidden; }

  /* PAGE HEADER */
  .tfm-page-header {
    display: flex; align-items: flex-end; justify-content: space-between;
    margin-bottom: 24px;
  }
  .tfm-page-title h1 {
    font-size: 22px; font-weight: 700; letter-spacing: -.4px; color: #1e2a4a;
  }
  .tfm-page-title p { font-size: 13px; color: #64748b; margin-top: 3px; }

  /* COPY BANNER */
  .tfm-copy-banner {
    display: flex; align-items: center; gap: 12px;
    background: #eff6ff;
    border: 1px solid #bfdbfe;
    border-radius: 12px; padding: 13px 18px; margin-bottom: 22px;
    cursor: pointer; user-select: none; transition: background .15s;
  }
  .tfm-copy-banner:hover { background: #dbeafe; }
  .tfm-copy-check {
    width: 20px; height: 20px; border-radius: 6px; flex-shrink: 0;
    border: 2px solid #93c5fd; background: #fff;
    display: grid; place-items: center; transition: all .15s;
  }
  .tfm-copy-check.checked { background: #1a56db; border-color: #1a56db; }
  .tfm-copy-label { font-size: 13.5px; color: #334155; }
  .tfm-copy-label strong { color: #1e2a4a; }

  /* ALERT */
  .tfm-alert {
    display: flex; align-items: center; gap: 10px;
    background: #f0fdf4; border: 1px solid #86efac;
    border-radius: 10px; padding: 12px 16px; margin-bottom: 20px;
    font-size: 13.5px; color: #166534;
  }

  /* MONTH CARD */
  .tfm-month-card {
    background: #fff;
    border: 1px solid #e2e8f8;
    border-radius: 12px; margin-bottom: 10px;
    overflow: hidden; transition: border-color .2s, box-shadow .2s;
  }
  .tfm-month-card:hover { border-color: #93c5fd; box-shadow: 0 2px 12px rgba(26,86,219,0.07); }

  .tfm-month-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 20px;
    border-bottom: 1px solid #f1f5fe;
    cursor: pointer; background: #fff;
  }
  .tfm-month-header:hover { background: #fafcff; }
  .tfm-month-left { display: flex; align-items: center; gap: 12px; }
  .tfm-month-dot {
    width: 9px; height: 9px; border-radius: 50%;
    background: #bfdbfe; flex-shrink: 0;
    transition: background .2s;
  }
  .tfm-month-card:hover .tfm-month-dot { background: #1a56db; }
  .tfm-month-name { font-size: 14.5px; font-weight: 600; color: #1e2a4a; }
  .tfm-month-badge {
    font-size: 11px; padding: 2px 9px; border-radius: 20px;
    font-family: 'DM Mono', monospace;
  }
  .tfm-month-badge.filled { background: #dcfce7; color: #166534; border: 1px solid #86efac; }
  .tfm-month-badge.empty  { background: #f8fafc; color: #94a3b8; border: 1px solid #e2e8f0; }
  .tfm-chevron { font-size: 12px; color: #94a3b8; transition: transform .2s; }
  .tfm-chevron.open { transform: rotate(180deg); }

  .tfm-month-body { padding: 20px; display: grid; grid-template-columns: 200px 1fr; gap: 24px; background: #fafcff; }

  /* DATE FIELD */
  .tfm-field-label {
    font-size: 11px; text-transform: uppercase; letter-spacing: .1em;
    color: #64748b; margin-bottom: 6px; font-weight: 500;
  }
  .tfm-input {
    width: 100%; background: #fff;
    border: 1px solid #cbd5e1;
    border-radius: 8px; padding: 9px 13px;
    color: #1e2a4a; font-family: 'DM Mono', monospace; font-size: 13px;
    outline: none; transition: border-color .15s, box-shadow .15s;
  }
  .tfm-input:focus { border-color: #1a56db; box-shadow: 0 0 0 3px rgba(26,86,219,0.1); }
  .tfm-input::placeholder { color: #cbd5e1; }

  /* FINE TYPE */
  .tfm-fine-section { display: flex; flex-direction: column; gap: 10px; }
  .tfm-fine-label-top { font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: #64748b; margin-bottom: 2px; font-weight: 500; }

  .tfm-fine-options { display: flex; gap: 10px; flex-wrap: wrap; }

  .tfm-radio-card {
    flex: 1; min-width: 120px;
    border: 1.5px solid #e2e8f0;
    border-radius: 10px; padding: 12px 14px;
    cursor: pointer; transition: all .15s; background: #fff;
    display: flex; flex-direction: column; gap: 8px;
  }
  .tfm-radio-card:hover { border-color: #93c5fd; background: #eff6ff; }
  .tfm-radio-card.selected { border-color: #1a56db; background: #eff6ff; }

  .tfm-radio-row { display: flex; align-items: center; gap: 8px; }
  .tfm-radio-dot {
    width: 16px; height: 16px; border-radius: 50%;
    border: 2px solid #cbd5e1; flex-shrink: 0;
    display: grid; place-items: center; transition: all .15s; background: #fff;
  }
  .tfm-radio-card.selected .tfm-radio-dot { border-color: #1a56db; }
  .tfm-radio-inner {
    width: 7px; height: 7px; border-radius: 50%;
    background: #1a56db; opacity: 0; transition: opacity .15s;
  }
  .tfm-radio-card.selected .tfm-radio-inner { opacity: 1; }
  .tfm-radio-name { font-size: 13px; font-weight: 600; color: #64748b; }
  .tfm-radio-card.selected .tfm-radio-name { color: #1a56db; }

  .tfm-sub-input {
    width: 100%; background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 7px; padding: 7px 10px;
    color: #1e2a4a; font-family: 'DM Mono', monospace; font-size: 13px;
    outline: none; transition: all .15s;
  }
  .tfm-sub-input:focus { border-color: #1a56db; box-shadow: 0 0 0 2px rgba(26,86,219,0.08); }
  .tfm-sub-input:disabled { opacity: .4; cursor: not-allowed; background: #f8fafc; }
  .tfm-sub-input::placeholder { color: #cbd5e1; }

  /* FOOTER */
  .tfm-footer {
    display: flex; align-items: center; justify-content: flex-end;
    padding: 18px 32px; gap: 12px;
    background: #fff; border-top: 1px solid #e2e8f8;
  }
  .tfm-btn-reset {
    padding: 10px 20px; border-radius: 9px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    color: #64748b; font-family: 'Inter', sans-serif; font-size: 14px;
    cursor: pointer; transition: all .15s; font-weight: 500;
  }
  .tfm-btn-reset:hover { background: #f1f5f9; color: #334155; border-color: #cbd5e1; }
  .tfm-btn-save {
    padding: 10px 28px; border-radius: 9px;
    background: #1a56db;
    border: none; color: #fff;
    font-family: 'Inter', sans-serif; font-size: 14px; font-weight: 600;
    cursor: pointer; transition: background .15s; letter-spacing: .1px;
  }
  .tfm-btn-save:hover { background: #1648c4; }

  /* SUCCESS TOAST */
  .tfm-toast {
    position: fixed; bottom: 28px; right: 28px;
    background: #fff; border: 1px solid #86efac;
    color: #166534; border-radius: 12px; padding: 14px 20px;
    font-size: 14px; font-weight: 500; display: flex; align-items: center; gap: 10px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.1);
    animation: slideUp .25s ease;
    z-index: 200;
  }
  @keyframes slideUp { from { transform:translateY(20px); opacity:0; } to { transform:translateY(0); opacity:1; } }

  @media (max-width: 860px) {
    .tfm-aside { display: none; }
    .tfm-main { padding: 20px; }
    .tfm-month-body { grid-template-columns: 1fr; }
  }
`;

// ─── SUBCOMPONENTS ─────────────────────────────────────────────────────────

function MonthCard({ month, data, onChange, open, onToggle }) {
  const hasFine = data.fine_type !== "";
  const isFilled = data.due_date !== "";

  const setField = (k, v) => onChange({ ...data, [k]: v });

  const selectFineType = (type) => {
    setField("fine_type", type === data.fine_type ? "" : type);
    if (type !== "percentage") setField("percentage", "");
    if (type !== "fix") setField("fine_amount", "");
  };

  return (
    <div className="tfm-month-card">
      <div className="tfm-month-header" onClick={onToggle}>
        <div className="tfm-month-left">
          <div className="tfm-month-dot" />
          <span className="tfm-month-name">{month.label}</span>
          <span className={`tfm-month-badge ${isFilled ? "filled" : "empty"}`}>
            {isFilled ? (hasFine ? "Due + Fine" : "Due set") : "Not configured"}
          </span>
        </div>
        <span className={`tfm-chevron ${open ? "open" : ""}`}>▼</span>
      </div>

      {open && (
        <div className="tfm-month-body">
          {/* Due Date */}
          <div>
            <div className="tfm-field-label">Due Date</div>
            <input
              type="date"
              className="tfm-input"
              value={data.due_date}
              onChange={(e) => setField("due_date", e.target.value)}
            />
          </div>

          {/* Fine Type */}
          <div className="tfm-fine-section">
            <div className="tfm-fine-label-top">Fine Type</div>
            <div className="tfm-fine-options">
              {/* None */}
              <div
                className={`tfm-radio-card ${data.fine_type === "" ? "selected" : ""}`}
                onClick={() => selectFineType("")}
                style={{ maxWidth: 110 }}
              >
                <div className="tfm-radio-row">
                  <div className="tfm-radio-dot">
                    <div className="tfm-radio-inner" />
                  </div>
                  <span className="tfm-radio-name">None</span>
                </div>
              </div>

              {/* Percentage */}
              <div
                className={`tfm-radio-card ${data.fine_type === "percentage" ? "selected" : ""}`}
                onClick={() => selectFineType("percentage")}
              >
                <div className="tfm-radio-row">
                  <div className="tfm-radio-dot">
                    <div className="tfm-radio-inner" />
                  </div>
                  <span className="tfm-radio-name">Percentage (%)</span>
                </div>
                <input
                  className="tfm-sub-input"
                  type="number"
                  min="0"
                  max="100"
                  step="0.1"
                  placeholder="e.g. 2.5"
                  disabled={data.fine_type !== "percentage"}
                  value={data.percentage}
                  onClick={(e) => e.stopPropagation()}
                  onChange={(e) => setField("percentage", e.target.value)}
                />
              </div>

              {/* Fixed Amount */}
              <div
                className={`tfm-radio-card ${data.fine_type === "fix" ? "selected" : ""}`}
                onClick={() => selectFineType("fix")}
              >
                <div className="tfm-radio-row">
                  <div className="tfm-radio-dot">
                    <div className="tfm-radio-inner" />
                  </div>
                  <span className="tfm-radio-name">
                    Fix Amount ({CURRENCY})
                  </span>
                </div>
                <input
                  className="tfm-sub-input"
                  type="number"
                  min="0"
                  step="1"
                  placeholder={`e.g. ${CURRENCY}50`}
                  disabled={data.fine_type !== "fix"}
                  value={data.fine_amount}
                  onClick={(e) => e.stopPropagation()}
                  onChange={(e) => setField("fine_amount", e.target.value)}
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── MAIN ──────────────────────────────────────────────────────────────────
export default function TransportFeesMaster() {
  const [rows, setRows] = useState(() =>
    Object.fromEntries(MONTHS.map((m) => [m.key, defaultRow()])),
  );
  const [openMonths, setOpenMonths] = useState({ april: true });
  const [copyAll, setCopyAll] = useState(false);
  const [toast, setToast] = useState("");
  const [saved, setSaved] = useState(false);

  const updateRow = useCallback((key, data) => {
    setRows((prev) => ({ ...prev, [key]: data }));
  }, []);

  const toggleMonth = (key) => setOpenMonths((p) => ({ ...p, [key]: !p[key] }));

  const handleCopyAll = () => {
    if (copyAll) {
      setCopyAll(false);
      return;
    }
    const first = rows[MONTHS[0].key];
    if (!first.due_date) {
      setToast("⚠️ Set April's due date first");
      setTimeout(() => setToast(""), 2500);
      return;
    }

    const baseDate = new Date(first.due_date);
    const updated = {};
    MONTHS.forEach((m, i) => {
      const d = new Date(baseDate);
      d.setMonth(d.getMonth() + i);
      const iso = d.toISOString().slice(0, 10);
      updated[m.key] = { ...first, due_date: iso };
    });
    setRows(updated);
    setOpenMonths(Object.fromEntries(MONTHS.map((m) => [m.key, true])));
    setCopyAll(true);
  };

  const handleSave = () => {
    const configured = MONTHS.filter((m) => rows[m.key].due_date);
    if (!configured.length) {
      setToast("⚠️ Configure at least one month");
      setTimeout(() => setToast(""), 2500);
      return;
    }
    setSaved(true);
    setToast(`✓ Saved ${configured.length} month(s) successfully`);
    setTimeout(() => setToast(""), 3000);
  };

  const handleReset = () => {
    setRows(Object.fromEntries(MONTHS.map((m) => [m.key, defaultRow()])));
    setOpenMonths({ april: true });
    setCopyAll(false);
    setSaved(false);
  };

  const configuredCount = MONTHS.filter((m) => rows[m.key].due_date).length;

  const navMain = [
    { icon: "🏠", label: "Front Office" },
    { icon: "👨‍🎓", label: "Student Info" },
    { icon: "💰", label: "Fees Collection" },
    { icon: "📊", label: "Income" },
    { icon: "💸", label: "Expenses" },
    { icon: "📝", label: "Examinations" },
    { icon: "📅", label: "Attendance" },
    { icon: "💻", label: "Online Exam" },
  ];
  const navRes = [
    { icon: "🚌", label: "Transport Fees", active: true },
    { icon: "📚", label: "Library" },
    { icon: "👥", label: "Human Resource" },
    { icon: "📢", label: "Communicate" },
  ];

  return (
    <>
      <style>{css}</style>
      <div className="tfm-root">
        {/* NAV */}
        <nav className="tfm-nav">
          <div className="tfm-nav-brand">
            <div className="tfm-nav-logo">🏫</div>
            <span className="tfm-nav-name">
              Demo <span>High School</span>
            </span>
          </div>
          <div className="tfm-nav-right">
            <div className="tfm-nav-chip">Session: 2026-27</div>
            <div className="tfm-avatar">T</div>
          </div>
        </nav>

        <div className="tfm-body">
          {/* SIDEBAR */}
          <aside className="tfm-aside">
            <div className="tfm-aside-sec">Main Menu</div>
            {navMain.map(({ icon, label }) => (
              <div key={label} className="tfm-aside-item">
                <span className="tfm-aside-icon">{icon}</span> {label}
              </div>
            ))}
            <div className="tfm-aside-sec">Resources</div>
            {navRes.map(({ icon, label, active }) => (
              <div
                key={label}
                className={`tfm-aside-item ${active ? "active" : ""}`}
              >
                <span className="tfm-aside-icon">{icon}</span> {label}
              </div>
            ))}
          </aside>

          {/* MAIN */}
          <main className="tfm-main">
            {/* Page Header */}
            <div className="tfm-page-header">
              <div className="tfm-page-title">
                <h1>🚌 Transport Fees Master</h1>
                <p>
                  Configure monthly due dates and fine rules for transport fees
                </p>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div
                  style={{
                    fontSize: 13,
                    color: "#1e2a4a",
                    background: "#dbeafe",
                    border: "1px solid #93c5fd",
                    borderRadius: 20,
                    padding: "4px 14px",
                  }}
                >
                  <span style={{ color: "#1a56db", fontWeight: 700 }}>
                    {configuredCount}
                  </span>{" "}
                  / {MONTHS.length} months
                </div>
              </div>
            </div>

            {/* Success alert */}
            {saved && configuredCount > 0 && (
              <div className="tfm-alert">
                ✓ &nbsp;Transport fees configuration saved for {configuredCount}{" "}
                month(s).
              </div>
            )}

            {/* Copy Banner */}
            <div className="tfm-copy-banner" onClick={handleCopyAll}>
              <div className={`tfm-copy-check ${copyAll ? "checked" : ""}`}>
                {copyAll && (
                  <span
                    style={{ color: "#fff", fontSize: 11, fontWeight: 700 }}
                  >
                    ✓
                  </span>
                )}
              </div>
              <div className="tfm-copy-label">
                <strong>Copy first month's settings</strong> to all remaining
                months{" "}
                <span style={{ fontSize: 12, color: "#404566" }}>
                  (auto-increments due dates)
                </span>
              </div>
            </div>

            {/* Month Cards */}
            {MONTHS.map((month) => (
              <MonthCard
                key={month.key}
                month={month}
                data={rows[month.key]}
                onChange={(data) => updateRow(month.key, data)}
                open={!!openMonths[month.key]}
                onToggle={() => toggleMonth(month.key)}
              />
            ))}
          </main>
        </div>

        {/* FOOTER */}
        <footer className="tfm-footer">
          <button className="tfm-btn-reset" onClick={handleReset}>
            Reset All
          </button>
          <button className="tfm-btn-save" onClick={handleSave}>
            Save Configuration
          </button>
        </footer>

        {/* TOAST */}
        {toast && <div className="tfm-toast">{toast}</div>}
      </div>
    </>
  );
}
