import { useEffect, useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { listCasesAdmin, type AdminCase, type ListCasesResponse } from "../../api/adminApi";

const STATUS_OPTIONS = [
  { value: "", label: "All Statuses" },
  { value: "created", label: "Created" },
  { value: "landmarks_detected", label: "Landmarks Detected" },
  { value: "landmarks_approved", label: "Landmarks Approved" },
  { value: "analysis_complete", label: "Analysis Complete" },
  { value: "processing_brace", label: "Processing Brace" },
  { value: "brace_generated", label: "Brace Generated" },
  { value: "brace_failed", label: "Brace Failed" },
];

const PAGE_SIZE = 20;

export default function AdminCases() {
  const navigate = useNavigate();
  
  const [data, setData] = useState<ListCasesResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Filters
  const [statusFilter, setStatusFilter] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("created_at");
  const [sortOrder, setSortOrder] = useState<"ASC" | "DESC">("DESC");
  const [currentPage, setCurrentPage] = useState(0);

  const loadCases = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await listCasesAdmin({
        status: statusFilter || undefined,
        search: searchQuery || undefined,
        sortBy,
        sortOrder,
        limit: PAGE_SIZE,
        offset: currentPage * PAGE_SIZE,
      });
      setData(result);
    } catch (err: any) {
      setError(err.message || "Failed to load cases");
    } finally {
      setLoading(false);
    }
  }, [statusFilter, searchQuery, sortBy, sortOrder, currentPage]);

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

  function handleSearch(e: React.FormEvent) {
    e.preventDefault();
    setCurrentPage(0);
    loadCases();
  }

  function handleSort(column: string) {
    if (sortBy === column) {
      setSortOrder(sortOrder === "ASC" ? "DESC" : "ASC");
    } else {
      setSortBy(column);
      setSortOrder("DESC");
    }
    setCurrentPage(0);
  }

  const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 0;

  function getStatusColor(status: string): string {
    switch (status) {
      case "brace_generated": return "bf-status-success";
      case "processing_brace": return "bf-status-warning";
      case "brace_failed": return "bf-status-error";
      case "landmarks_detected":
      case "landmarks_approved":
      case "analysis_complete": return "bf-status-info";
      default: return "bf-status-default";
    }
  }

  function extractRigoType(analysisResult: any): string | null {
    if (!analysisResult) return null;
    try {
      const result = typeof analysisResult === "string" 
        ? JSON.parse(analysisResult) 
        : analysisResult;
      return result.rigoType || result.rigo_classification?.type || null;
    } catch {
      return null;
    }
  }

  function extractCobbAngles(analysisResult: any, landmarksData: any): { PT?: number; MT?: number; TL?: number } | null {
    try {
      if (analysisResult) {
        const result = typeof analysisResult === "string" 
          ? JSON.parse(analysisResult) 
          : analysisResult;
        if (result.cobbAngles || result.cobb_angles) {
          return result.cobbAngles || result.cobb_angles;
        }
      }
      if (landmarksData) {
        const landmarks = typeof landmarksData === "string"
          ? JSON.parse(landmarksData)
          : landmarksData;
        return landmarks.cobb_angles || null;
      }
    } catch {
      // Ignore
    }
    return null;
  }

  return (
    <div className="bf-admin-page">
      <div className="bf-admin-header">
        <div>
          <h1>All Cases</h1>
          <p className="bf-admin-subtitle">
            {data ? `${data.total} total cases` : "Loading..."}
          </p>
        </div>
        <button className="btn" onClick={loadCases} disabled={loading}>
          Refresh
        </button>
      </div>

      {/* Filters */}
      <div className="bf-admin-filters">
        <form onSubmit={handleSearch} className="bf-admin-search-form">
          <input
            type="text"
            placeholder="Search by Case ID..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="bf-admin-search-input"
          />
          <button type="submit" className="btn">Search</button>
        </form>
        
        <select
          value={statusFilter}
          onChange={(e) => {
            setStatusFilter(e.target.value);
            setCurrentPage(0);
          }}
          className="bf-admin-filter-select"
        >
          {STATUS_OPTIONS.map((opt) => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          ))}
        </select>
      </div>

      {error && <div className="bf-admin-error">{error}</div>}

      {loading && !data ? (
        <div className="bf-admin-loading">Loading cases...</div>
      ) : data && data.cases.length > 0 ? (
        <>
          <div className="bf-admin-card bf-admin-table-container">
            <table className="bf-admin-table">
              <thead>
                <tr>
                  <th 
                    className="bf-admin-sortable"
                    onClick={() => handleSort("case_id")}
                  >
                    Case ID {sortBy === "case_id" && (sortOrder === "ASC" ? "↑" : "↓")}
                  </th>
                  <th 
                    className="bf-admin-sortable"
                    onClick={() => handleSort("status")}
                  >
                    Status {sortBy === "status" && (sortOrder === "ASC" ? "↑" : "↓")}
                  </th>
                  <th>Rigo Type</th>
                  <th>Cobb Angles</th>
                  <th>Body Scan</th>
                  <th 
                    className="bf-admin-sortable"
                    onClick={() => handleSort("created_at")}
                  >
                    Created {sortBy === "created_at" && (sortOrder === "ASC" ? "↑" : "↓")}
                  </th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {data.cases.map((c) => {
                  const rigoType = extractRigoType(c.analysis_result);
                  const cobbAngles = extractCobbAngles(c.analysis_result, c.landmarks_data);
                  
                  return (
                    <tr key={c.caseId}>
                      <td className="bf-admin-cell-caseid">
                        <code>{c.caseId}</code>
                      </td>
                      <td>
                        <span className={`bf-admin-case-status ${getStatusColor(c.status)}`}>
                          {c.status.replace(/_/g, " ")}
                        </span>
                      </td>
                      <td>
                        {rigoType ? (
                          <span className="bf-admin-rigo-badge">{rigoType}</span>
                        ) : "—"}
                      </td>
                      <td className="bf-admin-cell-cobb">
                        {cobbAngles ? (
                          <span className="bf-admin-cobb-inline">
                            {cobbAngles.PT !== undefined && <span>PT: {cobbAngles.PT}°</span>}
                            {cobbAngles.MT !== undefined && <span>MT: {cobbAngles.MT}°</span>}
                            {cobbAngles.TL !== undefined && <span>TL: {cobbAngles.TL}°</span>}
                          </span>
                        ) : "—"}
                      </td>
                      <td>
                        {c.body_scan_path ? (
                          <span className="bf-admin-badge-yes">Yes</span>
                        ) : (
                          <span className="bf-admin-badge-no">No</span>
                        )}
                      </td>
                      <td className="bf-admin-cell-date">
                        {new Date(c.created_at).toLocaleDateString()}
                        <br />
                        <span className="bf-admin-cell-time">
                          {new Date(c.created_at).toLocaleTimeString()}
                        </span>
                      </td>
                      <td>
                        <button
                          className="bf-admin-action-btn"
                          onClick={() => navigate(`/cases/${c.caseId}`)}
                        >
                          View
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="bf-admin-pagination">
              <button
                className="btn small"
                onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
                disabled={currentPage === 0}
              >
                Previous
              </button>
              <span className="bf-admin-page-info">
                Page {currentPage + 1} of {totalPages}
              </span>
              <button
                className="btn small"
                onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}
                disabled={currentPage >= totalPages - 1}
              >
                Next
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="bf-admin-empty-state">
          <p>No cases found</p>
          {(statusFilter || searchQuery) && (
            <button
              className="btn secondary"
              onClick={() => {
                setStatusFilter("");
                setSearchQuery("");
                setCurrentPage(0);
              }}
            >
              Clear Filters
            </button>
          )}
        </div>
      )}
    </div>
  );
}
