import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  getPatient,
  createPatientCase,
  type Patient,
  type PatientCase,
  formatPatientName,
  calculateAge,
  formatDate,
} from "../api/patientApi";
import { getDownloadUrl } from "../api/braceflowApi";

export default function PatientDetail() {
  const navigate = useNavigate();
  const { patientId } = useParams();

  const [patient, setPatient] = useState<Patient | null>(null);
  const [cases, setCases] = useState<PatientCase[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [creatingCase, setCreatingCase] = useState(false);
  const [thumbnails, setThumbnails] = useState<Record<string, string>>({});

  useEffect(() => {
    loadPatient();
  }, [patientId]);

  async function loadPatient() {
    try {
      const data = await getPatient(parseInt(patientId!));
      setPatient(data.patient);
      setCases(data.cases);
      // Load thumbnails for cases
      loadThumbnails(data.cases);
    } catch (err: any) {
      setError(err.message || "Failed to load patient");
    } finally {
      setLoading(false);
    }
  }

  async function loadThumbnails(caseList: PatientCase[]) {
    const newThumbnails: Record<string, string> = {};
    
    await Promise.all(
      caseList.map(async (c) => {
        try {
          const result = await getDownloadUrl(c.case_id, "xray");
          newThumbnails[c.case_id] = result.url;
        } catch {
          // No thumbnail available
        }
      })
    );
    
    setThumbnails(prev => ({ ...prev, ...newThumbnails }));
  }

  async function handleCreateCase() {
    setCreatingCase(true);
    setError(null);
    try {
      const result = await createPatientCase(parseInt(patientId!));
      // Navigate to the new case
      navigate(`/cases/${result.caseId}`);
    } catch (err: any) {
      setError(err.message || "Failed to create case");
      setCreatingCase(false);
    }
  }

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

  function formatStatus(status: string): string {
    return status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
  }

  if (loading) {
    return <div className="bf-loading">Loading patient...</div>;
  }

  if (!patient) {
    return (
      <div className="bf-error-state">
        <h2>Patient not found</h2>
        <button className="bf-btn bf-btn-primary" onClick={() => navigate("/patients")}>
          Back to Patients
        </button>
      </div>
    );
  }

  const age = calculateAge(patient.date_of_birth);

  return (
    <div className="bf-patient-detail-page">
      {/* Header */}
      <div className="bf-patient-detail-header">
        <button className="bf-back-btn" onClick={() => navigate("/patients")}>
          ← Back to Patients
        </button>
        <div className="bf-patient-detail-title">
          <div className="bf-patient-avatar-large">
            {patient.first_name[0]}
            {patient.last_name[0]}
          </div>
          <div>
            <h1>{formatPatientName(patient)}</h1>
            <div className="bf-patient-meta">
              {patient.mrn && <span className="bf-meta-item">MRN: {patient.mrn}</span>}
              {age && <span className="bf-meta-item">{age} years old</span>}
              {patient.gender && (
                <span className="bf-meta-item bf-capitalize">{patient.gender}</span>
              )}
              {!patient.is_active && (
                <span className="bf-badge bf-badge-inactive">Inactive</span>
              )}
            </div>
          </div>
        </div>
        <div className="bf-patient-detail-actions">
          <button
            className="bf-btn bf-btn-outline"
            onClick={() => navigate(`/patients/${patientId}/edit`)}
          >
            Edit Patient
          </button>
        </div>
      </div>

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

      <div className="bf-patient-detail-content">
        {/* Patient Information */}
        <div className="bf-patient-info-section">
          <div className="bf-info-card">
            <h3>Contact Information</h3>
            <div className="bf-info-grid">
              <div className="bf-info-item">
                <span className="bf-info-label">Email</span>
                <span className="bf-info-value">{patient.email || "-"}</span>
              </div>
              <div className="bf-info-item">
                <span className="bf-info-label">Phone</span>
                <span className="bf-info-value">{patient.phone || "-"}</span>
              </div>
              <div className="bf-info-item bf-info-item-full">
                <span className="bf-info-label">Address</span>
                <span className="bf-info-value">{patient.address || "-"}</span>
              </div>
            </div>
          </div>

          <div className="bf-info-card">
            <h3>Medical Information</h3>
            <div className="bf-info-grid">
              <div className="bf-info-item">
                <span className="bf-info-label">Diagnosis</span>
                <span className="bf-info-value">{patient.diagnosis || "-"}</span>
              </div>
              <div className="bf-info-item">
                <span className="bf-info-label">Curve Type</span>
                <span className="bf-info-value">
                  {patient.curve_type ? (
                    <span className="bf-curve-badge">{patient.curve_type}</span>
                  ) : (
                    "-"
                  )}
                </span>
              </div>
              <div className="bf-info-item">
                <span className="bf-info-label">Referring Physician</span>
                <span className="bf-info-value">{patient.referring_physician || "-"}</span>
              </div>
              <div className="bf-info-item">
                <span className="bf-info-label">Insurance</span>
                <span className="bf-info-value">{patient.insurance_info || "-"}</span>
              </div>
              {patient.medical_history && (
                <div className="bf-info-item bf-info-item-full">
                  <span className="bf-info-label">Medical History</span>
                  <span className="bf-info-value bf-info-text">
                    {patient.medical_history}
                  </span>
                </div>
              )}
              {patient.notes && (
                <div className="bf-info-item bf-info-item-full">
                  <span className="bf-info-label">Notes</span>
                  <span className="bf-info-value bf-info-text">{patient.notes}</span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Cases Section */}
        <div className="bf-patient-cases-section">
          <div className="bf-section-header">
            <h2>Cases ({cases.length})</h2>
            <button
              className="bf-btn bf-btn-small bf-btn-primary"
              onClick={handleCreateCase}
              disabled={creatingCase}
            >
              + New Case
            </button>
          </div>

          {cases.length > 0 ? (
            <div className="bf-cases-list">
              {cases.map((caseItem) => {
                // Parse analysis result for additional info
                let rigoType = null;
                let cobbAngles = null;
                try {
                  if (caseItem.analysis_result) {
                    const result =
                      typeof caseItem.analysis_result === "string"
                        ? JSON.parse(caseItem.analysis_result)
                        : caseItem.analysis_result;
                    rigoType = result.rigoType || result.rigo_classification?.type;
                    cobbAngles = result.cobbAngles || result.cobb_angles;
                  }
                } catch (e) {
                  /* ignore */
                }

                const thumbUrl = thumbnails[caseItem.case_id];
                
                return (
                  <div
                    key={caseItem.case_id}
                    className="bf-case-card bf-case-card-with-thumb"
                    onClick={() => navigate(`/cases/${caseItem.case_id}`)}
                  >
                    {/* X-ray Thumbnail */}
                    <div className="bf-case-card-thumb">
                      {thumbUrl ? (
                        <img src={thumbUrl} alt="X-ray" className="bf-case-thumb-img" />
                      ) : (
                        <div className="bf-case-thumb-placeholder">
                          <span>X</span>
                        </div>
                      )}
                    </div>

                    <div className="bf-case-card-content">
                      <div className="bf-case-card-header">
                        <div>
                          <span className="bf-case-id">{caseItem.case_id}</span>
                          {caseItem.visit_date && (
                            <span className="bf-case-date">
                              Visit: {formatDate(caseItem.visit_date)}
                            </span>
                          )}
                        </div>
                        <span className={`bf-status-badge ${getStatusColor(caseItem.status)}`}>
                          {formatStatus(caseItem.status)}
                        </span>
                      </div>

                      <div className="bf-case-card-body">
                        {rigoType && (
                          <div className="bf-case-detail">
                            <span className="bf-detail-label">Rigo Type:</span>
                            <span className="bf-rigo-badge">{rigoType}</span>
                          </div>
                        )}
                        {cobbAngles && (
                          <div className="bf-case-detail">
                            <span className="bf-detail-label">Cobb Angles:</span>
                            <span className="bf-cobb-values">
                              {cobbAngles.PT !== undefined && (
                                <span>PT: {cobbAngles.PT.toFixed(1)}°</span>
                              )}
                              {cobbAngles.MT !== undefined && (
                                <span>MT: {cobbAngles.MT.toFixed(1)}°</span>
                              )}
                              {cobbAngles.TL !== undefined && (
                                <span>TL: {cobbAngles.TL.toFixed(1)}°</span>
                              )}
                            </span>
                          </div>
                        )}
                        {caseItem.body_scan_url && (
                          <div className="bf-case-detail">
                            <span className="bf-detail-icon">📷</span>
                            <span>Body scan uploaded</span>
                          </div>
                        )}
                      </div>

                      <div className="bf-case-card-footer">
                        <span className="bf-case-created">
                          Created: {formatDate(caseItem.created_at)}
                        </span>
                        <span className="bf-case-arrow">→</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="bf-empty-cases">
              <p>No cases yet for this patient</p>
              <button
                className="bf-btn bf-btn-primary"
                onClick={handleCreateCase}
                disabled={creatingCase}
              >
                Create First Case
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
