import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { fetchCases, createCaseAndUploadXray, getDownloadUrl, deleteCase } from "../api/braceflowApi";
import type { CaseRecord } from "../api/braceflowApi";

export default function Dashboard({ onView }: { onView?: (id: string) => void }) {
  const nav = useNavigate();

  const [cases, setCases] = useState<CaseRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);

  // Upload state
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState("");
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Thumbnail URLs for each case
  const [thumbnails, setThumbnails] = useState<Record<string, string>>({});
  
  // Dropdown menu state
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  async function load() {
    setLoading(true);
    setErr(null);
    try {
      const c = await fetchCases();
      setCases(c);
      // Load thumbnails for each case
      loadThumbnails(c);
    } catch (e: any) {
      setErr(e?.message || "Failed to load cases");
      setCases([]);
    } finally {
      setLoading(false);
    }
  }

  // Load X-ray thumbnails for cases
  async function loadThumbnails(caseList: CaseRecord[]) {
    const newThumbnails: Record<string, string> = {};
    
    await Promise.all(
      caseList.map(async (c) => {
        try {
          const result = await getDownloadUrl(c.caseId, "xray");
          newThumbnails[c.caseId] = result.url;
        } catch {
          // No thumbnail available
        }
      })
    );
    
    setThumbnails(prev => ({ ...prev, ...newThumbnails }));
  }

  // Handle delete case
  async function handleDelete(caseId: string, e: React.MouseEvent) {
    e.stopPropagation();
    
    if (!confirm(`Are you sure you want to delete case "${caseId}"?\n\nThis will permanently remove the case and all associated files.`)) {
      return;
    }
    
    setDeleting(caseId);
    setOpenMenu(null);
    
    try {
      await deleteCase(caseId);
      setCases(prev => prev.filter(c => c.caseId !== caseId));
      setThumbnails(prev => {
        const updated = { ...prev };
        delete updated[caseId];
        return updated;
      });
    } catch (e: any) {
      setErr(e?.message || "Failed to delete case");
    } finally {
      setDeleting(null);
    }
  }

  // Close menu when clicking outside
  useEffect(() => {
    function handleClickOutside() {
      setOpenMenu(null);
    }
    document.addEventListener("click", handleClickOutside);
    return () => document.removeEventListener("click", handleClickOutside);
  }, []);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const c = await fetchCases();
        if (mounted) {
          setCases(c);
          loadThumbnails(c);
        }
      } catch (e: any) {
        if (mounted) setErr(e?.message || "Failed to load cases");
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => {
      mounted = false;
    };
  }, []);

  function viewCase(caseId: string) {
    if (onView) {
      onView(caseId);
      return;
    }
    nav(`/cases/${encodeURIComponent(caseId)}/analysis`);
  }

  const handleFileUpload = useCallback(async (file: File) => {
    if (!file.type.startsWith("image/")) {
      setErr("Please upload an image file (JPEG, PNG, etc.)");
      return;
    }

    setUploading(true);
    setErr(null);
    setUploadProgress("Creating case...");

    try {
      setUploadProgress("Uploading X-ray...");
      const { caseId } = await createCaseAndUploadXray(file);
      setUploadProgress("Complete!");
      
      // Refresh the case list and navigate to the new case
      await load();
      viewCase(caseId);
    } catch (e: any) {
      setErr(e?.message || "Upload failed");
    } finally {
      setUploading(false);
      setUploadProgress("");
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
    
    const file = e.dataTransfer.files[0];
    if (file) {
      handleFileUpload(file);
    }
  }, [handleFileUpload]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
  }, []);

  const handleFileInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileUpload(file);
    }
  }, [handleFileUpload]);

  const hasCases = cases.length > 0;

  return (
    <div className="bf-page bf-page--wide">
      <div className="bf-page-header">
        <div>
          <h1 className="bf-page-title">Cases</h1>
          <p className="bf-page-subtitle">Upload an X-ray to create a new case, or select an existing one.</p>
        </div>
        <div className="bf-spacer" />
        <div className="bf-toolbar">
          <button className="btn secondary bf-btn-fixed" onClick={load} disabled={loading || uploading}>
            {loading ? "Loading..." : "Refresh"}
          </button>
        </div>
      </div>

      {/* Upload Area */}
      <div 
        className={`bf-upload-zone ${dragActive ? "bf-upload-zone--active" : ""} ${uploading ? "bf-upload-zone--uploading" : ""}`}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={() => !uploading && fileInputRef.current?.click()}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileInputChange}
          style={{ display: "none" }}
          disabled={uploading}
        />
        {uploading ? (
          <div className="bf-upload-content">
            <div className="bf-upload-spinner"></div>
            <p className="bf-upload-text">{uploadProgress}</p>
          </div>
        ) : (
          <div className="bf-upload-content">
            <div className="bf-upload-icon">+</div>
            <p className="bf-upload-text">
              <strong>Click to upload</strong> or drag and drop an X-ray image
            </p>
            <p className="bf-upload-hint">JPEG, PNG, WebP supported</p>
          </div>
        )}
      </div>

      {err && <div className="error" style={{ marginTop: "1rem" }}>{err}</div>}

      {/* Cases List */}
      <div className="card" style={{ marginTop: "1.5rem" }}>
        <h2 className="bf-section-title">Recent Cases</h2>
        
        {loading ? (
          <div className="muted">Loading cases...</div>
        ) : !hasCases ? (
          <div className="bf-empty">No cases yet. Upload an X-ray above to create your first case.</div>
        ) : (
          <div className="bf-cases-list">
            {cases.map((c) => {
              const date = new Date(c.created_at);
              const isValidDate = !isNaN(date.getTime());
              const thumbUrl = thumbnails[c.caseId];
              const isDeleting = deleting === c.caseId;
              
              return (
                <div 
                  key={c.caseId} 
                  className={`bf-case-row ${isDeleting ? "bf-case-row--deleting" : ""}`}
                  onClick={() => !isDeleting && viewCase(c.caseId)}
                >
                  {/* Thumbnail */}
                  <div className="bf-case-thumb">
                    {thumbUrl ? (
                      <img src={thumbUrl} alt="X-ray" className="bf-case-thumb-img" />
                    ) : (
                      <div className="bf-case-thumb-placeholder">X</div>
                    )}
                  </div>
                  
                  {/* Case Info */}
                  <div className="bf-case-row-info">
                    <span className="bf-case-row-id">{c.caseId}</span>
                    {isValidDate && (
                      <span className="bf-case-row-date">
                        {date.toLocaleDateString()} {date.toLocaleTimeString()}
                      </span>
                    )}
                  </div>
                  
                  {/* Menu Button */}
                  <div className="bf-case-menu-container">
                    {isDeleting ? (
                      <div className="bf-case-menu-spinner"></div>
                    ) : (
                      <>
                        <button 
                          className="bf-case-menu-btn"
                          onClick={(e) => {
                            e.stopPropagation();
                            setOpenMenu(openMenu === c.caseId ? null : c.caseId);
                          }}
                        >
                          ⋮
                        </button>
                        {openMenu === c.caseId && (
                          <div className="bf-case-dropdown">
                            <button 
                              className="bf-case-dropdown-item bf-case-dropdown-item--danger"
                              onClick={(e) => handleDelete(c.caseId, e)}
                            >
                              Delete Case
                            </button>
                          </div>
                        )}
                      </>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
