// =============================================================
// NewRequest.jsx — Jauna Projekta Pieteikums
// =============================================================
// Klients:  Redz savu pieteikumu sarakstu + var iesniegt jaunu
// Admins:   Redz VISUS pieteikumus ar filtrēšanu
// =============================================================

import { useState, useEffect } from "react";
import { api } from "../../apiConfig";

// ── STATUS KONFIGURĀCIJA ──────────────────────────────────────
const STATUS_CFG = {
  JAUNS:        { label: "JAUNS",         bg: "#003b3b", color: "#00ccff", border: "#00ccff" },
  IZSKATISANA:  { label: "IZSKATĪŠANĀ",   bg: "#3b3b00", color: "#facc15", border: "#facc15" },
  APSTIPRINATS: { label: "APSTIPRINĀTS",  bg: "#003b00", color: "#00ff41", border: "#00ff41" },
  NORAIDS:      { label: "NORAIDĪTS",     bg: "#3b0000", color: "#ff4444", border: "#ff4444" },
};

const TIPS_OPTIONS = [
  { value: "WEB",            label: "🌐 Web izstrāde" },
  { value: "AI_BOTS",        label: "🤖 AI Čatbots / Asistents" },
  { value: "AUTOMATIZACIJA", label: "⚡ Biznesa automatizācija" },
  { value: "MOBILAIS",       label: "📱 Mobilā aplikācija" },
  { value: "CITS",           label: "💡 Cits" },
];

// ── GALVENĀ KOMPONENTE ────────────────────────────────────────
export default function NewRequest({ isAdmin }) {
  const [view, setView]           = useState("list");   // "list" | "form"
  const [requests, setRequests]   = useState([]);
  const [loading, setLoading]     = useState(true);
  const [error, setError]         = useState(null);
  const [selected, setSelected]   = useState(null);     // Detaļu skatīšanai

  // Veidlapas stāvoklis
  const [form, setForm] = useState({
    nosaukums: "", tips: "WEB", apraksts: "", budzets: "", termins: "",
  });
  const [submitting, setSubmitting] = useState(false);
  const [formError, setFormError]   = useState("");
  const [formSuccess, setFormSuccess] = useState(false);

  useEffect(() => {
    fetchRequests();
  }, []);

  const fetchRequests = async () => {
    setLoading(true);
    setError(null);
    try {
      const res  = await api.get("/api/pieteikumi/");
      const data = Array.isArray(res.data) ? res.data : res.data.results ?? [];
      setRequests(data);
    } catch (err) {
      setError("CONNECTION_ERROR — neizdevās ielādēt pieteikumus.");
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setFormError("");

    if (form.apraksts.length < 20) {
      return setFormError("VALIDATION_ERROR — apraksts pārāk īss (min. 20 rakstzīmes).");
    }

    setSubmitting(true);
    try {
      await api.post("/api/pieteikumi/", form);
      setFormSuccess(true);
      setForm({ nosaukums: "", tips: "WEB", apraksts: "", budzets: "", termins: "" });
      // Pēc 2s atgriežas sarakstā un atjauno
      setTimeout(() => {
        setFormSuccess(false);
        setView("list");
        fetchRequests();
      }, 2500);
    } catch (err) {
      const msg = err.response?.data?.apraksts?.[0]
        || err.response?.data?.nosaukums?.[0]
        || err.response?.data?.detail
        || "SERVER_ERROR — mēģini vēlreiz.";
      setFormError(String(msg).toUpperCase());
    } finally {
      setSubmitting(false);
    }
  };

  const setField = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  // ── STILI ─────────────────────────────────────────────────
  const s = {
    wrap:      { padding: "20px", color: "#00ff41", fontFamily: "'Courier New', monospace" },
    topBar:    { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px", borderBottom: "1px solid #1a7a35", paddingBottom: "15px", flexWrap: "wrap", gap: "10px" },
    title:     { fontSize: "13px", letterSpacing: "2px", color: "#00ff41" },
    newBtn:    { background: "#00ff41", color: "black", border: "none", padding: "10px 22px", fontWeight: "bold", cursor: "pointer", fontFamily: "'Courier New', monospace", fontSize: "11px", letterSpacing: "1px" },
    backBtn:   { background: "transparent", color: "#1a7a35", border: "1px solid #1a7a35", padding: "10px 22px", cursor: "pointer", fontFamily: "'Courier New', monospace", fontSize: "11px", letterSpacing: "1px" },

    // VEIDLAPA
    form:      { maxWidth: "680px" },
    group:     { marginBottom: "22px" },
    label:     { display: "block", color: "#1a7a35", fontSize: "10px", letterSpacing: "2px", textTransform: "uppercase", marginBottom: "7px" },
    input:     { width: "100%", padding: "12px", background: "rgba(0,0,0,0.5)", border: "1px solid #1a7a35", color: "#00ff41", fontFamily: "'Courier New', monospace", fontSize: "13px", outline: "none", boxSizing: "border-box", transition: "border 0.2s" },
    textarea:  { width: "100%", minHeight: "130px", padding: "12px", background: "rgba(0,0,0,0.5)", border: "1px solid #1a7a35", color: "#00ff41", fontFamily: "'Courier New', monospace", fontSize: "13px", outline: "none", resize: "vertical", boxSizing: "border-box" },
    select:    { width: "100%", padding: "12px", background: "#000", border: "1px solid #1a7a35", color: "#00ff41", fontFamily: "'Courier New', monospace", fontSize: "13px", outline: "none" },
    row2:      { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "15px" },
    submitBtn: (dis) => ({ width: "100%", padding: "15px", background: dis ? "#1a3a1a" : "#00ff41", color: dis ? "#1a7a35" : "black", border: "none", fontWeight: "bold", fontSize: "14px", letterSpacing: "2px", cursor: dis ? "not-allowed" : "pointer", fontFamily: "'Courier New', monospace", marginTop: "5px", transition: "all 0.2s" }),
    charCount: (n) => ({ fontSize: "10px", color: n < 20 ? "#ff4444" : "#1a7a35", textAlign: "right", marginTop: "4px" }),

    // SARAKSTS
    table:     { width: "100%", borderCollapse: "collapse", fontSize: "12px" },
    th:        { textAlign: "left", padding: "10px", borderBottom: "1px solid #1a7a35", color: "#1a7a35", fontSize: "10px", letterSpacing: "1px" },
    td:        { padding: "13px 10px", borderBottom: "1px solid rgba(0,255,65,0.07)", verticalAlign: "middle" },
    emptyBox:  { textAlign: "center", padding: "50px", border: "1px dashed #1a7a35", color: "#1a7a35" },
    errorBox:  { padding: "15px", border: "1px solid #ff4444", color: "#ff4444", background: "#1a0000", marginBottom: "15px" },
    successBox:{ padding: "20px", border: "1px solid #00ff41", color: "#00ff41", background: "rgba(0,50,0,0.5)", textAlign: "center", marginBottom: "15px" },

    // DETAĻU PANELIS
    detailOverlay: { position: "fixed", inset: 0, background: "rgba(0,0,0,0.75)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center" },
    detailBox:     { background: "#000d00", border: "1px solid #00ff41", padding: "35px", width: "560px", maxWidth: "95vw", maxHeight: "85vh", overflowY: "auto", position: "relative", fontFamily: "'Courier New', monospace" },
    detailTitle:   { color: "#00ff41", fontSize: "16px", letterSpacing: "3px", marginBottom: "25px", borderBottom: "1px solid #1a7a35", paddingBottom: "12px" },
    detailRow:     { display: "grid", gridTemplateColumns: "130px 1fr", gap: "8px", marginBottom: "12px", fontSize: "12px" },
    detailKey:     { color: "#1a7a35", letterSpacing: "1px" },
    detailVal:     { color: "#d1fae5" },
    closeDetBtn:   { position: "absolute", top: "12px", right: "15px", background: "none", border: "none", color: "#1a7a35", cursor: "pointer", fontSize: "12px", fontFamily: "'Courier New', monospace" },
    commentBox:    { marginTop: "20px", padding: "15px", border: "1px solid #1a7a35", background: "rgba(0,255,65,0.03)", fontSize: "12px", color: "#aaa", lineHeight: "1.6" },
  };

  const Badge = ({ status }) => {
    const cfg = STATUS_CFG[status] ?? { label: status, bg: "#222", color: "#666", border: "#666" };
    return (
      <span style={{ padding: "3px 8px", fontSize: "9px", fontWeight: "bold", letterSpacing: "1px", background: cfg.bg, color: cfg.color, border: `1px solid ${cfg.border}` }}>
        {cfg.label}
      </span>
    );
  };

  // ── RENDER: DETAĻU MODĀLS ─────────────────────────────────
  const DetailModal = () => {
    if (!selected) return null;
    const p = selected;
    return (
      <div style={s.detailOverlay} onClick={() => setSelected(null)}>
        <div style={s.detailBox} onClick={(e) => e.stopPropagation()}>
          <button style={s.closeDetBtn} onClick={() => setSelected(null)}>[CLOSE]</button>
          <div style={s.detailTitle}>// PIETEIKUMS #{p.id}</div>

          <div style={s.detailRow}><span style={s.detailKey}>NOSAUKUMS:</span>  <span style={s.detailVal}>{p.title}</span></div>
          <div style={s.detailRow}><span style={s.detailKey}>TIPS:</span>       <span style={s.detailVal}>{p.type_display}</span></div>
          <div style={s.detailRow}><span style={s.detailKey}>STATUSS:</span>    <span><Badge status={p.status} /></span></div>
          {isAdmin && <div style={s.detailRow}><span style={s.detailKey}>KLIENTS:</span>    <span style={s.detailVal}>{p.submitted_by}</span></div>}
          <div style={s.detailRow}><span style={s.detailKey}>BUDŽETS:</span>    <span style={{ ...s.detailVal, color: "#facc15" }}>{p.budget || "—"}</span></div>
          <div style={s.detailRow}><span style={s.detailKey}>TERMIŅŠ:</span>    <span style={s.detailVal}>{p.deadline || "—"}</span></div>
          <div style={s.detailRow}><span style={s.detailKey}>IESNIEGTS:</span>  <span style={{ ...s.detailVal, color: "#1a7a35" }}>{p.created_at}</span></div>

          <div style={{ marginTop: "18px" }}>
            <div style={{ ...s.detailKey, marginBottom: "8px" }}>APRAKSTS:</div>
            <div style={{ color: "#ccc", fontSize: "12px", lineHeight: "1.7", whiteSpace: "pre-wrap" }}>{p.description}</div>
          </div>

          {p.admin_comment && (
            <div style={s.commentBox}>
              <div style={{ color: "#00ff41", fontSize: "10px", letterSpacing: "1px", marginBottom: "8px" }}>💬 ADMINA ATBILDE:</div>
              {p.admin_comment}
            </div>
          )}
        </div>
      </div>
    );
  };

  // ── RENDER: VEIDLAPA ──────────────────────────────────────
  if (view === "form") return (
    <div style={s.wrap}>
      <div style={s.topBar}>
        <div style={s.title}>// JAUNS PROJEKTA PIETEIKUMS</div>
        <button style={s.backBtn} onClick={() => { setView("list"); setFormError(""); setFormSuccess(false); }}>
          ← ATCELT
        </button>
      </div>

      {formError   && <div style={s.errorBox}>⚠ {formError}</div>}
      {formSuccess && (
        <div style={s.successBox}>
          <div style={{ fontSize: "28px", marginBottom: "8px" }}>✔</div>
          PIETEIKUMS NOSŪTĪTS! Mēs ar Tevi sazināsimies 24h laikā.
          <div style={{ fontSize: "10px", color: "#1a7a35", marginTop: "8px" }}>ATGRIEŽAS SARAKSTĀ...</div>
        </div>
      )}

      {!formSuccess && (
        <form style={s.form} onSubmit={handleSubmit}>

          {/* NOSAUKUMS */}
          <div style={s.group}>
            <label style={s.label}>Projekta nosaukums *</label>
            <input
              style={s.input}
              placeholder="Piem: AI čatbots mājas lapai"
              value={form.nosaukums}
              onChange={setField("nosaukums")}
              required
              onFocus={(e) => (e.target.style.border = "1px solid #00ff41")}
              onBlur={(e)  => (e.target.style.border = "1px solid #1a7a35")}
            />
          </div>

          {/* TIPS */}
          <div style={s.group}>
            <label style={s.label}>Projekta tips *</label>
            <select style={s.select} value={form.tips} onChange={setField("tips")}>
              {TIPS_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>{o.label}</option>
              ))}
            </select>
          </div>

          {/* APRAKSTS */}
          <div style={s.group}>
            <label style={s.label}>Detalizēts apraksts * <span style={{ color: "#1a3a1a" }}>(min. 20 rakstzīmes)</span></label>
            <textarea
              style={s.textarea}
              placeholder="Ko vēlaties sasniegt? Kādas funkcijas nepieciešamas? Kāda ir mērķauditorija?"
              value={form.apraksts}
              onChange={setField("apraksts")}
              required
              onFocus={(e) => (e.target.style.border = "1px solid #00ff41")}
              onBlur={(e)  => (e.target.style.border = "1px solid #1a7a35")}
            />
            <div style={s.charCount(form.apraksts.length)}>
              {form.apraksts.length} / min. 20 rakstzīmes
            </div>
          </div>

          {/* BUDŽETS + TERMIŅŠ */}
          <div style={{ ...s.group, ...s.row2 }}>
            <div>
              <label style={s.label}>Aptuvens budžets</label>
              <input
                style={s.input}
                placeholder="Piem: €500–€1500"
                value={form.budzets}
                onChange={setField("budzets")}
                onFocus={(e) => (e.target.style.border = "1px solid #00ff41")}
                onBlur={(e)  => (e.target.style.border = "1px solid #1a7a35")}
              />
            </div>
            <div>
              <label style={s.label}>Vēlamais termiņš</label>
              <input
                style={s.input}
                placeholder="Piem: 1 mēnesis"
                value={form.termins}
                onChange={setField("termins")}
                onFocus={(e) => (e.target.style.border = "1px solid #00ff41")}
                onBlur={(e)  => (e.target.style.border = "1px solid #1a7a35")}
              />
            </div>
          </div>

          <button
            type="submit"
            disabled={submitting}
            style={s.submitBtn(submitting)}
            onMouseEnter={(e) => { if (!submitting) e.target.style.background = "#ffffff"; }}
            onMouseLeave={(e) => { if (!submitting) e.target.style.background = "#00ff41"; }}
          >
            {submitting ? "SENDING..." : "IESNIEGT_PIETEIKUMU →"}
          </button>
        </form>
      )}
    </div>
  );

  // ── RENDER: SARAKSTS ──────────────────────────────────────
  return (
    <div style={s.wrap}>
      <div style={s.topBar}>
        <div>
          <div style={s.title}>
            {isAdmin ? "// VISI PIETEIKUMI" : "// MANI PIETEIKUMI"}
          </div>
          {!loading && (
            <div style={{ fontSize: "10px", color: "#1a7a35", marginTop: "4px" }}>
              KOPĀ: {requests.length} IERAKSTS(-I)
            </div>
          )}
        </div>

        {/* Jauna pieteikuma poga — tikai klientam */}
        {!isAdmin && (
          <button style={s.newBtn} onClick={() => setView("form")}>
            + JAUNS PIETEIKUMS
          </button>
        )}
      </div>

      {/* IELĀDE */}
      {loading && <div style={{ textAlign: "center", padding: "40px", color: "#1a7a35" }}>⟳ LOADING...</div>}

      {/* KĻŪDA */}
      {!loading && error && (
        <div style={s.errorBox}>
          ⚠ {error}
          <button onClick={fetchRequests} style={{ marginLeft: "15px", background: "none", border: "1px solid #ff4444", color: "#ff4444", padding: "5px 12px", cursor: "pointer", fontFamily: "'Courier New', monospace" }}>
            RETRY
          </button>
        </div>
      )}

      {/* TUKŠS */}
      {!loading && !error && requests.length === 0 && (
        <div style={s.emptyBox}>
          {isAdmin
            ? "NO_REQUESTS_FOUND — nav iesniegtu pieteikumu."
            : (
              <>
                <div style={{ marginBottom: "15px" }}>NO_REQUESTS — vēl nav iesniegtu pieteikumu.</div>
                <button style={s.newBtn} onClick={() => setView("form")}>
                  + IESNIEGT PIRMO PIETEIKUMU
                </button>
              </>
            )
          }
        </div>
      )}

      {/* TABULA */}
      {!loading && !error && requests.length > 0 && (
        <table style={s.table}>
          <thead>
            <tr>
              <th style={s.th}>#</th>
              <th style={s.th}>NOSAUKUMS</th>
              {isAdmin && <th style={s.th}>KLIENTS</th>}
              <th style={s.th}>TIPS</th>
              <th style={s.th}>STATUSS</th>
              <th style={s.th}>DATUMS</th>
              <th style={s.th}>DETAĻAS</th>
            </tr>
          </thead>
          <tbody>
            {requests.map((p) => (
              <tr
                key={p.id}
                onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(0,255,65,0.02)")}
                onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}
              >
                <td style={{ ...s.td, color: "#1a7a35", fontSize: "11px" }}>#{p.id}</td>
                <td style={{ ...s.td, fontWeight: "bold", maxWidth: "220px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {p.title}
                </td>
                {isAdmin && <td style={{ ...s.td, color: "#aaa", fontSize: "11px" }}>{p.submitted_by}</td>}
                <td style={{ ...s.td, color: "#888", fontSize: "11px" }}>{p.type_display}</td>
                <td style={s.td}><Badge status={p.status} /></td>
                <td style={{ ...s.td, color: "#1a7a35", fontSize: "11px" }}>{p.created_at?.slice(0, 10)}</td>
                <td style={s.td}>
                  <button
                    onClick={() => setSelected(p)}
                    style={{ background: "transparent", border: "1px solid #1a7a35", color: "#1a7a35", padding: "5px 12px", cursor: "pointer", fontFamily: "'Courier New', monospace", fontSize: "10px", letterSpacing: "1px" }}
                    onMouseEnter={(e) => { e.target.style.borderColor = "#00ff41"; e.target.style.color = "#00ff41"; }}
                    onMouseLeave={(e) => { e.target.style.borderColor = "#1a7a35"; e.target.style.color = "#1a7a35"; }}
                  >
                    VIEW →
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      {/* DETAĻU MODĀLS */}
      <DetailModal />
    </div>
  );
}
