"use client";

// Client island for the per-project Data tab: approves/imports mine data roots,
// triggers mines_data_import, and shows live import progress.

import { useCallback, useEffect, useRef, useState } from "react";

function pct(progress) {
  const total = progress?.total_files || 0;
  if (!total) return 0;
  const done = (progress?.complete || 0) + (progress?.failed || 0) + (progress?.skipped || 0);
  return Math.min(100, Math.round((done / total) * 100));
}

function basename(value) {
  const parts = String(value || "").split(/[\\/]+/).filter(Boolean);
  return parts.at(-1) || value || "Selected folder";
}

export default function ImportPanel({ minesProjectId, initialProgress }) {
  const [directory, setDirectory] = useState("");
  const [approvedRoots, setApprovedRoots] = useState([]);
  const [progress, setProgress] = useState(initialProgress || null);
  const [running, setRunning] = useState(false);
  const [picking, setPicking] = useState(false);
  const [approving, setApproving] = useState(false);
  const [error, setError] = useState(null);
  const [notice, setNotice] = useState(null);
  const pollRef = useRef(null);

  const fetchProgress = useCallback(async () => {
    try {
      const res = await fetch(`/api/mines/projects/${minesProjectId}/import`, { cache: "no-store" });
      if (!res.ok) return;
      const json = await res.json();
      if (json?.data) setProgress(json.data);
    } catch {
      // transient — keep last known progress
    }
  }, [minesProjectId]);

  const fetchRoots = useCallback(async () => {
    try {
      const res = await fetch("/api/mines/import-roots", { cache: "no-store" });
      if (!res.ok) return;
      const json = await res.json();
      if (Array.isArray(json?.roots)) setApprovedRoots(json.roots);
    } catch {
      // keep last known roots
    }
  }, []);

  useEffect(() => {
    fetchProgress();
    fetchRoots();
    pollRef.current = setInterval(() => {
      fetchProgress();
    }, 5000);
    return () => clearInterval(pollRef.current);
  }, [fetchProgress, fetchRoots]);

  const active = (progress?.queued || 0) + (progress?.running || 0) > 0;

  const approveTypedFolder = useCallback(async () => {
    setError(null);
    setNotice(null);
    const chosen = directory.trim();
    if (!chosen) {
      setError("Enter or choose the folder you want to approve for Mines import.");
      return null;
    }
    setApproving(true);
    try {
      const res = await fetch("/api/mines/import-roots", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ directory_path: chosen, label: basename(chosen) }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || json?.status !== "ok") {
        setError(`Could not approve folder: ${json?.error || "unknown error"}`);
        return null;
      }
      setDirectory(json.root_path || chosen);
      setNotice(json.existing ? "Folder was already approved for Mines import." : "Folder approved for Mines import.");
      fetchRoots();
      return json.root_path || chosen;
    } catch (err) {
      setError(`Could not approve folder: ${err?.message || "network error"}`);
      return null;
    } finally {
      setApproving(false);
    }
  }, [directory, fetchRoots]);

  const chooseFolder = useCallback(async () => {
    setError(null);
    setNotice(null);
    setPicking(true);
    try {
      const res = await fetch("/api/fs/pick-folder", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: "Choose a Mines data folder",
          start_path: directory.trim() || undefined,
          register_import_root: true,
          label: "Mines data folder",
        }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || json?.error) {
        if (json?.error !== "cancelled") setError(`Folder selection failed: ${json?.error || "unknown error"}`);
        return;
      }
      setDirectory(json.folder_path || "");
      setNotice("Folder selected and approved for Mines import.");
      fetchRoots();
    } catch (err) {
      setError(`Folder selection failed: ${err?.message || "network error"}`);
    } finally {
      setPicking(false);
    }
  }, [directory, fetchRoots]);

  const runImport = useCallback(async () => {
    setError(null);
    setNotice(null);
    let chosen = directory.trim();
    if (!chosen) {
      setError("Choose or paste the folder containing the mine data.");
      return;
    }

    const approved = approvedRoots.some(root => chosen === root.root_path || chosen.startsWith(`${root.root_path}/`));
    if (!approved) {
      const approvedPath = await approveTypedFolder();
      if (!approvedPath) return;
      chosen = approvedPath;
    }

    setRunning(true);
    try {
      const res = await fetch(`/api/mines/projects/${minesProjectId}/import`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ directory_path: chosen, resume: true }),
      });
      const json = await res.json().catch(() => ({}));
      if (json?.status === "approval_required") {
        setNotice("Import is waiting for approval. Approve it in the approvals queue, then run again.");
      } else if (json?.status === "ok") {
        setNotice(`Queued ${json.queued ?? 0} files (${json.catalog_only ?? 0} catalog-only, ${json.skipped_complete ?? 0} already imported).`);
        fetchProgress();
        fetchRoots();
      } else if (json?.error) {
        setError(`Import failed: ${json.error}`);
      } else {
        setNotice("Import request submitted.");
      }
    } catch (err) {
      setError(`Import request failed: ${err?.message || "network error"}`);
    } finally {
      setRunning(false);
    }
  }, [approvedRoots, approveTypedFolder, directory, minesProjectId, fetchProgress, fetchRoots]);

  const barPct = pct(progress);
  const busy = running || picking || approving;

  return (
    <div
      style={{
        border: "1px solid rgba(17,19,24,.08)",
        borderRadius: 18,
        background: "linear-gradient(145deg, rgba(255,255,255,.9), rgba(247,244,237,.78))",
        padding: 18,
        marginBottom: 20,
        boxShadow: "0 18px 45px rgba(17,19,24,.06)",
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12, gap: 12, flexWrap: "wrap" }}>
        <div>
          <span style={{ display: "block", fontSize: 13, fontWeight: 800, color: "#111318" }}>Import mine data</span>
          <span style={{ display: "block", marginTop: 3, fontSize: 11.5, color: "#68707b" }}>
            Choose a local source folder once; MadarX remembers approved Mines import roots.
          </span>
        </div>
        {active && (
          <span style={{ fontSize: 11.5, fontWeight: 700, color: "#c2452a" }}>
            {progress.running || 0} processing · {progress.queued || 0} queued
          </span>
        )}
      </div>

      {approvedRoots.length > 0 && (
        <label style={{ display: "block", marginBottom: 10 }}>
          <span style={{ display: "block", marginBottom: 5, fontSize: 11.5, fontWeight: 750, color: "#343943" }}>Approved folders</span>
          <select
            value={directory}
            onChange={(e) => setDirectory(e.target.value)}
            style={{ width: "100%", padding: "9px 12px", border: "1px solid rgba(17,19,24,.14)", borderRadius: 10, fontSize: 13 }}
          >
            <option value="">Select a previously approved folder…</option>
            {approvedRoots.map(root => (
              <option key={root.id} value={root.root_path}>{root.label} — {root.root_path}</option>
            ))}
          </select>
        </label>
      )}

      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <input
          type="text"
          value={directory}
          onChange={(e) => setDirectory(e.target.value)}
          placeholder="Choose a folder or paste an absolute path"
          spellCheck={false}
          aria-label="Mines data folder path"
          style={{
            flex: 1,
            minWidth: 260,
            padding: "10px 12px",
            border: "1px solid rgba(17,19,24,.14)",
            borderRadius: 10,
            fontSize: 13,
            fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
          }}
        />
        <button
          type="button"
          onClick={chooseFolder}
          disabled={busy}
          style={{ padding: "10px 14px", borderRadius: 10, border: "1px solid rgba(17,19,24,.14)", background: "#fff", color: "#111318", fontSize: 13, fontWeight: 750, cursor: busy ? "wait" : "pointer" }}
        >
          {picking ? "Choosing…" : "Choose folder"}
        </button>
        <button
          type="button"
          onClick={approveTypedFolder}
          disabled={busy || !directory.trim()}
          style={{ padding: "10px 14px", borderRadius: 10, border: "1px solid rgba(194,69,42,.28)", background: "rgba(194,69,42,.07)", color: "#8f321f", fontSize: 13, fontWeight: 750, cursor: busy ? "wait" : "pointer" }}
        >
          {approving ? "Approving…" : "Approve folder"}
        </button>
        <button
          type="button"
          onClick={runImport}
          disabled={busy || !directory.trim()}
          style={{
            padding: "10px 18px",
            borderRadius: 10,
            border: "none",
            background: busy ? "#9aa0aa" : "#2A5C45",
            color: "#fff",
            fontSize: 13,
            fontWeight: 800,
            cursor: busy ? "wait" : "pointer",
          }}
        >
          {running ? "Submitting…" : "Run import"}
        </button>
      </div>

      <p style={{ margin: "9px 0 0", fontSize: 11.5, color: "#68707b" }}>
        Approval is saved inside MadarX. Imports stay bounded to folders you approve here, and each run remains audit-logged.
      </p>

      {(notice || error) && (
        <p aria-live="polite" style={{ margin: "10px 0 0", fontSize: 12.5, color: error ? "#c2452a" : "#2A5C45", fontWeight: 700 }}>
          {error || notice}
        </p>
      )}

      {progress && progress.total_files > 0 && (
        <div style={{ marginTop: 14 }}>
          <div style={{ height: 8, borderRadius: 6, background: "rgba(17,19,24,.08)", overflow: "hidden" }}>
            <div style={{ width: `${barPct}%`, height: "100%", background: "#2A5C45", transition: "width .4s ease" }} />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 11, color: "#68707b", gap: 8, flexWrap: "wrap" }}>
            <span>{barPct}% processed</span>
            <span>
              {progress.complete || 0} complete · {progress.failed || 0} failed · {progress.skipped || 0} skipped · {progress.total_files || 0} total
            </span>
          </div>
        </div>
      )}
    </div>
  );
}
