import { useState, useEffect } from "react";
import { useTheme } from "../useTheme";
import Badge from "./Badge";
import DocStatusBar from "./DocStatusBar";
import ConfirmVisitModal from "./ConfirmVisitModal";

function daysLabel(days) {
  if (days === undefined || days === null) return <span className="font-mono font-medium text-[var(--text-muted)]">—</span>;
  if (days < 0)
    return <span className="font-mono font-semibold text-[#FF7070]">Expired {Math.abs(days)}d ago</span>;
  if (days <= 7)
    return <span className="font-mono font-medium text-[#FF7070]">{days} days</span>;
  if (days <= 30)
    return <span className="font-mono font-medium text-[var(--accent-text)]">{days} days</span>;
  return <span className="font-mono font-medium text-[var(--text-primary)]">{days} days</span>;
}

function scoreClass(priority) {
  if (priority >= 1000) return "text-[#B00000]";
  if (priority >= 500) return "text-[var(--accent-text)]";
  if (priority >= 200) return "text-[var(--text-secondary)]";
  return "text-[var(--text-muted)]";
}

const FILTERS = [
  { key: "all", label: "All" },
  { key: "at-risk", label: "At Risk" },
  { key: "action-needed", label: "Action Needed" },
  { key: "RESUPPLY_READY", label: "Clear to Ship" },
  { key: "ACTIVE", label: "On Track" },
];

const AT_RISK_FLAGS = ["SUPPLY_LAPSED", "VISIT_REQUIRED", "RENEWAL_CRITICAL"];
const ACTION_NEEDED_FLAGS = ["RENEWAL_ELEVATED", "RENEWAL_SOON", "TRANSFER_PENDING"];

const HIGH_PRIORITY_FLAGS = ["SUPPLY_LAPSED", "VISIT_REQUIRED", "RENEWAL_CRITICAL", "TRANSFER_PENDING"];
const CONFIRM_VISIT_FLAGS = ["VISIT_REQUIRED", "RENEWAL_CRITICAL", "RENEWAL_ELEVATED", "RENEWAL_SOON"];

export default function WorklistTable({ records, activeFilter, onFilterChange }) {
  const { dark } = useTheme();
  const [expandedRow, setExpandedRow] = useState(null);
  const [confirmingRecord, setConfirmingRecord] = useState(null);
  const [localRecords, setLocalRecords] = useState(records);

  useEffect(() => { setLocalRecords(records); }, [records]);

  function handleVisitConfirmed(patientId, updatedRecord) {
    setLocalRecords(prev =>
      prev.map(r => r.patient_id === patientId ? { ...r, ...updatedRecord } : r)
        .sort((a, b) => (b.priority_score || b.priority || 0) - (a.priority_score || a.priority || 0))
    );
  }

  const filtered =
    activeFilter === "all"
      ? localRecords
      : activeFilter === "at-risk"
      ? localRecords.filter((r) => AT_RISK_FLAGS.includes(r.flag))
      : activeFilter === "action-needed"
      ? localRecords.filter((r) => ACTION_NEEDED_FLAGS.includes(r.flag))
      : localRecords.filter((r) => r.flag === activeFilter);

  const todayStr = new Date().toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });

  return (
    <div className="bg-[var(--bg-card)] border border-[var(--border-color)] rounded-[10px] shadow-[var(--shadow-card-md)] overflow-hidden transition-colors">
      {/* Header */}
      <div className="flex items-center justify-between px-[22px] py-4 border-b border-[var(--border-color)] bg-[var(--bg-elevated)] gap-4 flex-wrap">
        <div>
          <div className="font-heading font-bold text-[15px] text-[var(--text-heading)]">
            Outreach Worklist
          </div>
          <div className="font-mono text-[11px] text-[var(--text-muted)] mt-[2px]">
            {localRecords.length} patients · sorted by priority score · {todayStr}
          </div>
        </div>
        <div className="flex gap-[6px] flex-wrap">
          {FILTERS.map((f) => (
            <button
              key={f.key}
              onClick={() => onFilterChange(f.key)}
              className={`px-3 py-1 rounded-full text-[11.5px] cursor-pointer font-body transition-all border ${
                activeFilter === f.key
                  ? "bg-[var(--brand)] text-white border-[var(--brand)]"
                  : "bg-transparent border-[var(--border-color)] text-[var(--text-secondary)] hover:border-[var(--brand)] hover:text-[var(--brand)]"
              }`}
            >
              {f.label}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <table className="w-full border-collapse">
        <thead>
          <tr>
            {["Patient ID", "Device", "Payer", "Days Left", "Status", "Priority", "Action"].map(h => (
              <th key={h} className="px-[22px] py-[10px] text-left text-[10.5px] font-semibold tracking-[0.06em] uppercase text-[var(--text-muted)] bg-[var(--bg-elevated)] border-b border-[var(--border-color)] whitespace-nowrap">
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {filtered.map((r, i) => {
            const hp = HIGH_PRIORITY_FLAGS.includes(r.flag);
            const rowKey = r.patient_id + "-" + i;
            const isExpanded = expandedRow === rowKey;
            const showConfirmVisit = CONFIRM_VISIT_FLAGS.includes(r.flag) || r.visit_date_confidence === "estimated";
            // Support both API shape (days_until_coverage_end) and legacy local shape (daysUntilEnd)
            const daysLeft = r.days_until_coverage_end ?? r.daysUntilEnd;
            const priority = r.priority_score ?? r.priority;
            const deviceDisplay = r.device_display || r.device_type;

            return (
              <>
                <tr
                  key={rowKey}
                  className={`border-b border-[var(--border-subtle)] transition-colors cursor-pointer hover:bg-[var(--row-hover)] ${
                    hp
                      ? dark
                        ? "bg-[rgba(224,104,48,0.09)] hover:bg-[rgba(203,107,32,0.14)]"
                        : "bg-[rgba(224,96,40,0.05)] hover:bg-[rgba(203,107,32,0.14)]"
                      : ""
                  }`}
                  onClick={() => setExpandedRow(isExpanded ? null : rowKey)}
                >
                  <td className="px-[22px] py-[13px] align-middle">
                    <div className={`font-mono text-[12.5px] font-bold ${hp ? "text-[var(--accent-text)]" : "text-[var(--text-secondary)]"}`}>
                      {r.patient_id}
                    </div>
                    {i === 0 && (
                      <div className="font-mono text-[9.5px] font-semibold tracking-[0.06em] text-[var(--accent-text)] mt-[2px]">
                        ★ TOP PRIORITY
                      </div>
                    )}
                    {r.visit_date_confidence === "estimated" && (
                      <div className="text-[9px] text-[#CB6B20] mt-[2px]">Estimated visit date</div>
                    )}
                  </td>
                  <td className="px-[22px] py-[13px] text-[13.5px] font-medium text-[var(--text-primary)] align-middle">
                    {deviceDisplay}
                  </td>
                  <td className="px-[22px] py-[13px] text-[13px] text-[var(--text-secondary)] align-middle">
                    {r.payer}
                  </td>
                  <td className="px-[22px] py-[13px] align-middle">
                    {daysLabel(daysLeft)}
                  </td>
                  <td className="px-[22px] py-[13px] align-middle">
                    <div className="flex items-center gap-[8px]">
                      <Badge flag={r.flag} />
                      {r.doc_state && <DocStatusBar docState={r.doc_state} />}
                    </div>
                    {r.reason && (
                      <div className="text-[10.5px] text-[var(--text-muted)] mt-[4px] max-w-[260px] leading-[1.4]">
                        {r.reason}
                      </div>
                    )}
                  </td>
                  <td className="px-[22px] py-[13px] align-middle">
                    <span className={`font-mono text-[16px] font-medium ${scoreClass(priority)}`}>
                      {priority}
                    </span>
                  </td>
                  <td className="px-[22px] py-[13px] align-middle" onClick={e => e.stopPropagation()}>
                    {showConfirmVisit ? (
                      <button
                        onClick={() => setConfirmingRecord(r)}
                        className="bg-transparent border border-[var(--accent)] text-[var(--accent-text)] px-[13px] py-[5px] rounded-md text-xs cursor-pointer font-body whitespace-nowrap transition-all hover:bg-[rgba(203,107,32,0.1)]"
                      >
                        Confirm Visit →
                      </button>
                    ) : (
                      <ActionButton flag={r.flag} />
                    )}
                  </td>
                </tr>

                {/* Expanded row — cascade + doc checklist */}
                {isExpanded && (
                  <tr key={rowKey + "-expanded"} className="bg-[var(--bg-elevated)]">
                    <td colSpan={7} className="px-[32px] py-[16px]">
                      {r.cascade && r.cascade.length > 0 && (
                        <div className="mb-4">
                          <div className="text-[11px] font-semibold text-[#CC2222] uppercase tracking-[0.06em] mb-2">
                            Documentation Cascade
                          </div>
                          <div className="text-[12px] text-[var(--text-secondary)] font-mono">
                            {r.cascade.join(" → ")}
                          </div>
                        </div>
                      )}
                      {r.doc_state && (
                        <div>
                          <div className="text-[11px] font-semibold text-[var(--text-muted)] uppercase tracking-[0.06em] mb-2">
                            Documentation Checklist
                          </div>
                          <div className="grid grid-cols-2 gap-y-[6px] gap-x-[20px] text-[12px]">
                            <DocItem label="SWO" value={r.doc_state.swo} />
                            <DocItem label="Qualifying Visit" value={r.doc_state.visit} />
                            <DocItem label="PECOS Enrollment" value={r.doc_state.pecos} />
                            <DocItem label="Prior Authorization" value={r.doc_state.pa} />
                            <DocItem label="Diagnosis on File" value={r.doc_state.diagnosis} />
                          </div>
                        </div>
                      )}
                      {!r.doc_state && !r.cascade?.length && (
                        <div className="text-[12px] text-[var(--text-muted)]">No documentation details available. Upload a CSV with doc columns to see the full checklist.</div>
                      )}
                    </td>
                  </tr>
                )}
              </>
            );
          })}
          {filtered.length === 0 && (
            <tr>
              <td colSpan={7} className="px-[22px] py-8 text-center text-[var(--text-muted)]">
                No patients match this filter.
              </td>
            </tr>
          )}
        </tbody>
      </table>

      {/* Footer */}
      <div className="flex items-center justify-between px-[22px] py-3 border-t border-[var(--border-subtle)] text-[11px] text-[var(--text-muted)] bg-[var(--bg-elevated)]">
        <span className="flex items-center gap-[6px] text-[var(--text-secondary)]">
          PHI-safe — patient names and DOBs never stored. Crosswalk: patient_id only.
        </span>
        <span>
          {activeFilter === "all"
            ? `${localRecords.length} patients · all results shown`
            : `${filtered.length} of ${localRecords.length} · filtered`}
        </span>
      </div>

      {/* Confirm Visit Modal */}
      {confirmingRecord && (
        <ConfirmVisitModal
          record={confirmingRecord}
          onClose={() => setConfirmingRecord(null)}
          onConfirmed={handleVisitConfirmed}
        />
      )}
    </div>
  );
}

function ActionButton({ flag }) {
  const base =
    "bg-transparent border border-[var(--border-color)] text-[var(--text-secondary)] px-[13px] py-[5px] rounded-md text-xs cursor-pointer font-body whitespace-nowrap transition-all hover:border-[var(--brand)] hover:text-[var(--brand)]";

  if (flag === "SUPPLY_LAPSED" || flag === "VISIT_REQUIRED") {
    return <button className={`${base} !border-[var(--accent)] !text-[var(--accent-text)] hover:bg-[rgba(203,107,32,0.1)]`}>Contact Prescriber</button>;
  }
  if (flag === "TRANSFER_PENDING") {
    return <button className={`${base} !border-[var(--accent)] !text-[var(--accent-text)] hover:bg-[rgba(203,107,32,0.1)]`}>Verify Docs</button>;
  }
  if (flag === "RESUPPLY_READY") {
    return <button className={base}>Initiate Resupply</button>;
  }
  return <button className={base}>View</button>;
}

function DocItem({ label, value }) {
  const isGood = value && (
    value === "On File" || value === "Verified" || value === "Not Required" ||
    value.startsWith("Confirmed") || value.startsWith("Approved") || value === "N/A"
  );
  const isBad = value && (
    value === "Missing" || value === "Not Verified" || value === "Expired" ||
    value === "Denied" || value === "Required — Not Started"
  );
  const color = isGood ? "text-[#1A8040]" : isBad ? "text-[#CC2222]" : "text-[#CB6B20]";

  return (
    <div className="flex items-start gap-[6px]">
      <span className="text-[var(--text-muted)] w-[140px] shrink-0">{label}:</span>
      <span className={`font-medium ${color}`}>{value || "Unknown"}</span>
    </div>
  );
}
