"use client";

import { useState, useCallback, useEffect } from "react";
import { useRouter } from "next/navigation";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** Derive a text label from a 0..1 completeness score. */
function completenessLabel(value) {
  if (value === null || value === undefined) return null;
  if (value >= 0.8) return "full";
  if (value >= 0.4) return "partial";
  return "low";
}

function CompletenessBadge({ value }) {
  const label = completenessLabel(value);
  if (!label) {
    return <span className="admin-muted">—</span>;
  }
  const toneMap = {
    full: "ready",
    partial: "warn",
    low: "danger",
  };
  return <span className={`admin-pill ${toneMap[label]}`}>{label}</span>;
}

// Inline SVG icons — no emojis, no external deps beyond what the project already has.
function IconFilter() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M2 4h12M5 8h6M7 12h2" strokeLinecap="round" />
    </svg>
  );
}

function IconUpload() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M8 11V4M5 7l3-3 3 3" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M3 13h10" strokeLinecap="round" />
    </svg>
  );
}

function IconChevronLeft() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M10 12L6 8l4-4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconChevronRight() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M6 12l4-4-4-4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function IconClose() {
  return (
    <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
      <path d="M4 4l8 8M12 4l-8 8" strokeLinecap="round" />
    </svg>
  );
}

// ---------------------------------------------------------------------------
// Import form (inline, revealed on button click)
// ---------------------------------------------------------------------------

function ImportForm({ onClose, onImported }) {
  const [fileId, setFileId] = useState("");
  const [portfolioName, setPortfolioName] = useState("");
  const [status, setStatus] = useState(null); // null | "pending" | "error"
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setBusy(true);
    setStatus(null);
    try {
      const res = await fetch("/api/mines/portfolio", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ file_id: fileId, portfolio_name: portfolioName }),
      });
      const json = await res.json();
      // The POST route returns executeRegistryTool's result with HTTP 200 even
      // for gate/error outcomes, so branch on the result shape, not res.ok alone.
      if (!res.ok) {
        setStatus("error");
        setMessage(json?.error || "Import failed. Check the file ID and try again.");
      } else if (json?.status === "approval_required") {
        // Medium-risk gated tool: an approval request was created.
        setStatus("pending");
        setMessage("Import queued for approval. Visit the Approvals page to authorize it.");
      } else if (json?.status === "ok") {
        const created = json.entries_created ?? 0;
        const updated = json.entries_updated ?? 0;
        setStatus("success");
        setMessage(`Imported ${created} new and ${updated} updated entries.`);
        if (typeof onImported === "function") onImported();
      } else {
        // Adapter error (file_not_found, missing_required_column, …) or any
        // other non-success status — surface it rather than faking success.
        setStatus("error");
        setMessage(
          json?.reason || json?.error || json?.status || "Import failed. Check the file ID and try again."
        );
      }
    } catch {
      setStatus("error");
      setMessage("Network error. Please check your connection and try again.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div
      role="region"
      aria-label="Import catalog"
      style={{
        border: "1px solid rgba(17,19,24,.10)",
        borderRadius: 14,
        background: "#fff",
        padding: "16px 18px",
        marginTop: 12,
        boxShadow: "0 8px 24px rgba(17,19,24,.08)",
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <span style={{ fontSize: 13, fontWeight: 750, color: "#111318", letterSpacing: "-.01em" }}>
          Import catalog
        </span>
        <button
          onClick={onClose}
          aria-label="Close import form"
          style={{
            border: 0,
            background: "transparent",
            cursor: "pointer",
            color: "#68707b",
            display: "grid",
            placeItems: "center",
            width: 24,
            height: 24,
            borderRadius: 6,
          }}
        >
          <IconClose />
        </button>
      </div>

      {status === "pending" && (
        <div className="mkt-toast info" role="status" style={{ marginBottom: 12 }}>
          <span>Pending</span>
          <p>{message}</p>
        </div>
      )}
      {status === "success" && (
        <div className="mkt-toast success" role="status" style={{ marginBottom: 12 }}>
          <span>Imported</span>
          <p>{message}</p>
        </div>
      )}
      {status === "error" && (
        <div className="mkt-toast error" role="alert" style={{ marginBottom: 12 }}>
          <span>Error</span>
          <p>{message}</p>
        </div>
      )}

      {status !== "pending" && status !== "success" && (
        <form onSubmit={handleSubmit} className="admin-form-grid" style={{ gap: 10 }}>
          <div className="admin-field">
            <span>File ID</span>
            <input
              type="text"
              required
              placeholder="e.g. file_abc123"
              value={fileId}
              onChange={(e) => setFileId(e.target.value)}
              autoComplete="off"
            />
          </div>
          <div className="admin-field">
            <span>Portfolio name</span>
            <input
              type="text"
              required
              placeholder="e.g. SPM Tabla Proyectos Q2"
              value={portfolioName}
              onChange={(e) => setPortfolioName(e.target.value)}
              autoComplete="off"
            />
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
            <button
              type="button"
              onClick={onClose}
              className="admin-btn-sm"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={busy || !fileId.trim() || !portfolioName.trim()}
              className="admin-btn-primary"
              aria-busy={busy}
            >
              {busy ? "Importing…" : "Import"}
            </button>
          </div>
        </form>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Filter toolbar
// ---------------------------------------------------------------------------

const COMPLETENESS_OPTIONS = [
  { value: "", label: "Any completeness" },
  { value: "full", label: "Full" },
  { value: "partial", label: "Partial" },
  { value: "low", label: "Low" },
];

const SORT_OPTIONS = [
  { value: "name", label: "Name" },
  { value: "commodity", label: "Commodity" },
  { value: "data_completeness", label: "Completeness" },
];

function FilterToolbar({ filters, onChange }) {
  return (
    <div
      role="search"
      aria-label="Portfolio filters"
      style={{
        display: "flex",
        flexWrap: "wrap",
        gap: 10,
        alignItems: "flex-end",
        padding: "14px 16px",
        background: "rgba(245,246,248,.72)",
        borderRadius: 14,
        border: "1px solid rgba(17,19,24,.07)",
        marginBottom: 16,
      }}
    >
      {/* Commodity */}
      <label className="admin-field" style={{ minWidth: 140, flex: "1 1 140px" }}>
        <span>Commodity</span>
        <input
          type="text"
          placeholder="e.g. gold, copper"
          value={filters.commodity}
          onChange={(e) => onChange({ ...filters, commodity: e.target.value, offset: 0 })}
          aria-label="Filter by commodity"
        />
      </label>

      {/* Deposit type */}
      <label className="admin-field" style={{ minWidth: 140, flex: "1 1 140px" }}>
        <span>Deposit type</span>
        <input
          type="text"
          placeholder="e.g. porphyry"
          value={filters.deposit_type}
          onChange={(e) => onChange({ ...filters, deposit_type: e.target.value, offset: 0 })}
          aria-label="Filter by deposit type"
        />
      </label>

      {/* Completeness */}
      <label className="admin-field" style={{ minWidth: 130, flex: "0 0 auto" }}>
        <span>Completeness</span>
        <select
          className="admin-select"
          value={filters.data_completeness}
          onChange={(e) => onChange({ ...filters, data_completeness: e.target.value, offset: 0 })}
          aria-label="Filter by data completeness"
        >
          {COMPLETENESS_OPTIONS.map((o) => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      </label>

      {/* Has drilling toggle */}
      <label
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 6,
          flex: "0 0 auto",
        }}
      >
        <span
          style={{
            fontSize: 10.5,
            fontWeight: 850,
            letterSpacing: ".10em",
            textTransform: "uppercase",
            color: "#68707b",
          }}
        >
          Has drilling
        </span>
        <label
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            cursor: "pointer",
            height: 38,
            padding: "0 10px",
            border: "1px solid rgba(17,19,24,.10)",
            borderRadius: 12,
            background: "#fff",
            userSelect: "none",
          }}
        >
          <input
            type="checkbox"
            checked={filters.has_drilling}
            onChange={(e) => onChange({ ...filters, has_drilling: e.target.checked, offset: 0 })}
            style={{ accentColor: "#111318", width: 14, height: 14 }}
            aria-label="Show only drilled projects"
          />
          <span style={{ fontSize: 12.5, color: "#313740" }}>Drilled only</span>
        </label>
      </label>

      {/* Sort */}
      <label className="admin-field" style={{ minWidth: 130, flex: "0 0 auto", marginLeft: "auto" }}>
        <span>Sort by</span>
        <select
          className="admin-select"
          value={filters.sort}
          onChange={(e) => onChange({ ...filters, sort: e.target.value, offset: 0 })}
          aria-label="Sort portfolio"
        >
          {SORT_OPTIONS.map((o) => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      </label>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main grid
// ---------------------------------------------------------------------------

const PAGE_LIMIT = 50;

const DEFAULT_FILTERS = {
  commodity: "",
  deposit_type: "",
  has_drilling: false,
  data_completeness: "",
  sort: "name",
  offset: 0,
};

export default function ScreeningGrid() {
  const router = useRouter();
  const [filters, setFilters] = useState(DEFAULT_FILTERS);
  const [data, setData] = useState(null);      // null = not yet loaded
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showImport, setShowImport] = useState(false);

  const fetchPortfolio = useCallback(async (currentFilters) => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (currentFilters.commodity.trim())   params.set("commodity", currentFilters.commodity.trim());
      if (currentFilters.deposit_type.trim()) params.set("deposit_type", currentFilters.deposit_type.trim());
      if (currentFilters.has_drilling)        params.set("has_drilling", "1");
      if (currentFilters.data_completeness)  params.set("data_completeness", currentFilters.data_completeness);
      params.set("sort",   currentFilters.sort);
      params.set("limit",  String(PAGE_LIMIT));
      params.set("offset", String(currentFilters.offset));

      const res = await fetch(`/api/mines/portfolio?${params.toString()}`);
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body?.error || `Request failed (HTTP ${res.status})`);
      }
      const json = await res.json();
      setData(json);
    } catch (err) {
      setError(err.message || "Failed to load portfolio");
    } finally {
      setLoading(false);
    }
  }, []);

  // Re-fetch whenever filters change.
  useEffect(() => {
    fetchPortfolio(filters);
  }, [filters, fetchPortfolio]);

  function handleRowClick(entry) {
    // The overview page is keyed on the portfolio entry id and resolves the
    // linked project internally. Routing by project_id would 404.
    router.push(`/mines/${entry.id}`);
  }

  function handlePrev() {
    setFilters((f) => ({ ...f, offset: Math.max(0, f.offset - PAGE_LIMIT) }));
  }
  function handleNext() {
    if (!data) return;
    setFilters((f) => ({ ...f, offset: f.offset + PAGE_LIMIT }));
  }

  const entries = data?.data ?? [];
  const meta    = data?.meta ?? { total: 0, filtered: 0, limit: PAGE_LIMIT, offset: 0 };
  const hasMore = meta.offset + entries.length < meta.filtered;
  const hasPrev = meta.offset > 0;

  return (
    <div className="mkt-page" data-page="mines-portfolio">
      {/* ── Header row ── */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, marginBottom: 8 }}>
        <div />
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <button
            onClick={() => setShowImport((v) => !v)}
            className="admin-button secondary"
            aria-expanded={showImport}
            aria-controls="import-form-panel"
          >
            <IconUpload />
            Import catalog
          </button>
        </div>
      </div>

      {/* ── Import form ── */}
      {showImport && (
        <div id="import-form-panel">
          <ImportForm onClose={() => setShowImport(false)} onImported={() => fetchPortfolio(filters)} />
        </div>
      )}

      {/* ── Stat strip ── */}
      {data && (
        <div
          style={{
            display: "flex",
            gap: 0,
            marginTop: 12,
            marginBottom: 20,
            borderTop: "1px solid rgba(17,19,24,.10)",
            borderBottom: "1px solid rgba(17,19,24,.10)",
            padding: "16px 0",
          }}
        >
          {[
            { label: "Total projects", value: meta.total },
            { label: "Showing", value: meta.filtered },
          ].map(({ label, value }) => (
            <div
              key={label}
              style={{
                paddingRight: 32,
                marginRight: 32,
                borderRight: "1px solid rgba(17,19,24,.07)",
              }}
            >
              <b style={{ display: "block", fontSize: 34, fontWeight: 300, letterSpacing: "-.05em", lineHeight: 1 }}>{value}</b>
              <span style={{ display: "block", marginTop: 8, fontSize: 10.5, fontWeight: 650, letterSpacing: ".14em", textTransform: "uppercase", color: "#8a8f99" }}>{label}</span>
            </div>
          ))}
        </div>
      )}

      {/* ── Filters ── */}
      <FilterToolbar filters={filters} onChange={setFilters} />

      {/* ── States: loading / error / empty / table ── */}
      {loading && (
        <div className="admin-empty" aria-live="polite" aria-busy="true" style={{ minHeight: 180, display: "grid", placeItems: "center" }}>
          <div>
            <div className="skel" style={{ width: 120, height: 12, borderRadius: 8, marginBottom: 10 }} />
            <div className="skel" style={{ width: 220, height: 10, borderRadius: 6 }} />
          </div>
        </div>
      )}

      {!loading && error && (
        <div className="admin-record needs-action" role="alert">
          <div className="admin-record-top">
            <b>Failed to load portfolio</b>
          </div>
          <p>{error}</p>
          <div className="admin-inline-actions">
            <button className="admin-btn-sm" onClick={() => fetchPortfolio(filters)}>
              Retry
            </button>
          </div>
        </div>
      )}

      {!loading && !error && meta.total === 0 && (
        <div className="admin-empty" style={{ minHeight: 240, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 12 }}>
          <div
            style={{
              width: 40,
              height: 40,
              borderRadius: 12,
              background: "rgba(17,19,24,.06)",
              display: "grid",
              placeItems: "center",
              color: "#68707b",
              marginBottom: 4,
            }}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
              <path d="M3 7h18M3 12h18M3 17h18" strokeLinecap="round" />
            </svg>
          </div>
          <b style={{ fontSize: 15, letterSpacing: "-.015em" }}>No catalog imported yet</b>
          <p style={{ margin: 0, maxWidth: 320, textAlign: "center", lineHeight: 1.6 }}>
            Use &ldquo;Import catalog&rdquo; to load your SPM tabla proyectos spreadsheet.
          </p>
          <button
            className="admin-button mars"
            style={{ marginTop: 4 }}
            onClick={() => setShowImport(true)}
          >
            <IconUpload />
            Import catalog
          </button>
        </div>
      )}

      {!loading && !error && meta.total > 0 && entries.length === 0 && (
        <div className="admin-empty" role="status">
          <b>No results</b>
          <p>No projects match the current filters. Clear filters to see all entries.</p>
        </div>
      )}

      {!loading && !error && entries.length > 0 && (
        <>
          <div className="admin-table-wrap">
            <table className="admin-table" aria-label="Portfolio screening table">
              <thead>
                <tr>
                  <th scope="col" style={{ width: 44 }}>#</th>
                  <th scope="col">Project</th>
                  <th scope="col">Commodity</th>
                  <th scope="col">Deposit / Target type</th>
                  <th scope="col" style={{ width: 88 }}>Drilling</th>
                  <th scope="col" style={{ width: 100 }}>Completeness</th>
                  <th scope="col">Deal terms</th>
                  <th scope="col">Available information</th>
                </tr>
              </thead>
              <tbody>
                {entries.map((entry) => (
                  <tr
                    key={entry.id}
                    onClick={() => handleRowClick(entry)}
                    style={{ cursor: "pointer", transition: "background .12s" }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(17,19,24,.025)")}
                    onMouseLeave={(e) => (e.currentTarget.style.background = "")}
                    tabIndex={0}
                    aria-label={`Open ${entry.name}`}
                    onKeyDown={(e) => {
                      if (e.key === "Enter" || e.key === " ") handleRowClick(entry);
                    }}
                  >
                    <td style={{ color: "#9aa0aa", fontVariantNumeric: "tabular-nums", fontFamily: "ui-monospace, monospace", fontSize: 11 }}>
                      {entry.consecutive ?? "—"}
                    </td>
                    <td>
                      <b style={{ fontSize: 12.5, letterSpacing: "-.01em" }}>{entry.name || "—"}</b>
                      {entry.owner ? (
                        <small style={{ display: "block", color: "#7a818c", marginTop: 2 }}>
                          {entry.owner}
                        </small>
                      ) : null}
                    </td>
                    <td>
                      <span style={{ fontSize: 12.5, color: "#313740" }}>{entry.commodity || <span className="admin-muted">—</span>}</span>
                    </td>
                    <td>
                      <span style={{ fontSize: 12.5, color: "#313740" }}>{entry.deposit_type || <span className="admin-muted">—</span>}</span>
                    </td>
                    <td>
                      {entry.has_drilling ? (
                        <span className="admin-pill ready">Yes</span>
                      ) : (
                        <span className="admin-pill neutral">No</span>
                      )}
                    </td>
                    <td>
                      <CompletenessBadge value={entry.data_completeness} />
                    </td>
                    <td>
                      {entry.deal_terms ? (
                        <span
                          title={entry.deal_terms}
                          style={{
                            fontSize: 12.5,
                            color: "#555d68",
                            display: "-webkit-box",
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: "vertical",
                            overflow: "hidden",
                            maxWidth: 200,
                          }}
                        >
                          {entry.deal_terms}
                        </span>
                      ) : (
                        <span className="admin-muted">—</span>
                      )}
                    </td>
                    <td>
                      {entry.available_information ? (
                        <span
                          title={entry.available_information}
                          style={{
                            fontSize: 12.5,
                            color: "#555d68",
                            display: "-webkit-box",
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: "vertical",
                            overflow: "hidden",
                            maxWidth: 200,
                          }}
                        >
                          {entry.available_information}
                        </span>
                      ) : (
                        <span className="admin-muted">—</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* ── Pagination ── */}
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              marginTop: 16,
              gap: 12,
            }}
          >
            <span style={{ fontSize: 12, color: "#68707b" }}>
              Showing {meta.offset + 1}–{meta.offset + entries.length} of {meta.filtered}
              {meta.filtered !== meta.total ? ` (${meta.total} total)` : ""}
            </span>
            <div style={{ display: "flex", gap: 6 }}>
              <button
                className="admin-btn-sm"
                onClick={handlePrev}
                disabled={!hasPrev}
                aria-label="Previous page"
              >
                <IconChevronLeft />
                Prev
              </button>
              <button
                className="admin-btn-sm"
                onClick={handleNext}
                disabled={!hasMore}
                aria-label="Next page"
              >
                Next
                <IconChevronRight />
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
