import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  listPatients,
  archivePatient,
  type Patient,
  formatPatientName,
  calculateAge,
  formatDate,
} from "../api/patientApi";

export default function PatientList() {
  const navigate = useNavigate();
  const [patients, setPatients] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);

  // Filters
  const [search, setSearch] = useState("");
  const [limit] = useState(20);
  const [offset, setOffset] = useState(0);

  // Archive confirmation
  const [archiveConfirm, setArchiveConfirm] = useState<Patient | null>(null);

  useEffect(() => {
    loadPatients();
  }, [search, offset]);

  async function loadPatients() {
    setLoading(true);
    setError(null);
    try {
      const data = await listPatients({
        search: search || undefined,
        isActive: true,
        limit,
        offset,
      });
      setPatients(data.patients);
      setTotal(data.total);
    } catch (err: any) {
      setError(err.message || "Failed to load patients");
    } finally {
      setLoading(false);
    }
  }

  async function handleArchive(patient: Patient) {
    try {
      await archivePatient(patient.id);
      setArchiveConfirm(null);
      loadPatients();
    } catch (err: any) {
      setError(err.message || "Failed to archive patient");
    }
  }

  function handleSearchChange(e: React.ChangeEvent<HTMLInputElement>) {
    setSearch(e.target.value);
    setOffset(0);
  }

  const totalPages = Math.ceil(total / limit);
  const currentPage = Math.floor(offset / limit) + 1;

  return (
    <div className="bf-patients-page">
      <div className="bf-patients-header">
        <div>
          <h1>Patients</h1>
          <p className="bf-patients-subtitle">
            Manage patient records and create new cases
          </p>
        </div>
        <button
          className="bf-btn bf-btn-primary bf-add-patient-btn"
          onClick={() => navigate("/patients/new")}
        >
          <span className="bf-btn-icon">+</span>
          Add Patient
        </button>
      </div>

      {/* Filters */}
      <div className="bf-patients-filters">
        <div className="bf-search-box">
          <input
            type="text"
            placeholder="Search by name, MRN, or email..."
            value={search}
            onChange={handleSearchChange}
            className="bf-search-input"
          />
        </div>
      </div>

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

      {loading ? (
        <div className="bf-loading">Loading patients...</div>
      ) : patients.length > 0 ? (
        <>
          <div className="bf-patients-grid">
            {patients.map((patient) => (
              <div
                key={patient.id}
                className={`bf-patient-card ${!patient.is_active ? "inactive" : ""}`}
                onClick={() => navigate(`/patients/${patient.id}`)}
              >
                <div className="bf-patient-card-header">
                  <div className="bf-patient-avatar">
                    {patient.first_name[0]}
                    {patient.last_name[0]}
                  </div>
                  <div className="bf-patient-info">
                    <h3 className="bf-patient-name">
                      {formatPatientName(patient)}
                    </h3>
                    {patient.mrn && (
                      <span className="bf-patient-mrn">MRN: {patient.mrn}</span>
                    )}
                  </div>
                  {!patient.is_active && (
                    <span className="bf-badge bf-badge-inactive">Inactive</span>
                  )}
                </div>

                <div className="bf-patient-card-body">
                  <div className="bf-patient-details">
                    {patient.date_of_birth && (
                      <div className="bf-patient-detail">
                        <span className="bf-detail-label">Age:</span>
                        <span className="bf-detail-value">
                          {calculateAge(patient.date_of_birth)} years
                        </span>
                      </div>
                    )}
                    {patient.gender && (
                      <div className="bf-patient-detail">
                        <span className="bf-detail-label">Gender:</span>
                        <span className="bf-detail-value bf-capitalize">
                          {patient.gender}
                        </span>
                      </div>
                    )}
                    {patient.diagnosis && (
                      <div className="bf-patient-detail">
                        <span className="bf-detail-label">Diagnosis:</span>
                        <span className="bf-detail-value">{patient.diagnosis}</span>
                      </div>
                    )}
                  </div>

                  <div className="bf-patient-stats">
                    <div className="bf-patient-stat">
                      <span className="bf-stat-value">{patient.case_count || 0}</span>
                      <span className="bf-stat-label">Cases</span>
                    </div>
                    {patient.last_visit && (
                      <div className="bf-patient-stat">
                        <span className="bf-stat-value">{formatDate(patient.last_visit)}</span>
                        <span className="bf-stat-label">Last Visit</span>
                      </div>
                    )}
                  </div>
                </div>

                <div className="bf-patient-card-actions" onClick={(e) => e.stopPropagation()}>
                  <button
                    className="bf-btn bf-btn-small bf-btn-outline"
                    onClick={() => navigate(`/patients/${patient.id}/edit`)}
                  >
                    Edit
                  </button>
                  <button
                    className="bf-btn bf-btn-small bf-btn-outline bf-btn-danger"
                    onClick={() => setArchiveConfirm(patient)}
                  >
                    Delete
                  </button>
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="bf-pagination">
              <span className="bf-pagination-info">
                Showing {offset + 1} - {Math.min(offset + limit, total)} of {total} patients
              </span>
              <div className="bf-pagination-controls">
                <button
                  className="bf-btn bf-btn-small"
                  disabled={offset === 0}
                  onClick={() => setOffset(Math.max(0, offset - limit))}
                >
                  Previous
                </button>
                <span className="bf-pagination-page">
                  Page {currentPage} of {totalPages}
                </span>
                <button
                  className="bf-btn bf-btn-small"
                  disabled={offset + limit >= total}
                  onClick={() => setOffset(offset + limit)}
                >
                  Next
                </button>
              </div>
            </div>
          )}
        </>
      ) : (
        <div className="bf-empty-state">
          <div className="bf-empty-icon">👤</div>
          <h3>No patients found</h3>
          <p>
            {search
              ? "Try adjusting your search criteria"
              : "Get started by adding your first patient"}
          </p>
          {!search && (
            <button
              className="bf-btn bf-btn-primary"
              onClick={() => navigate("/patients/new")}
            >
              Add First Patient
            </button>
          )}
        </div>
      )}

      {/* Delete Confirmation Modal (archives behind the scenes) */}
      {archiveConfirm && (
        <div className="bf-modal-backdrop" onClick={() => setArchiveConfirm(null)}>
          <div className="bf-modal" onClick={(e) => e.stopPropagation()}>
            <h2>Delete Patient</h2>
            <p>
              Are you sure you want to delete{" "}
              <strong>{formatPatientName(archiveConfirm)}</strong>?
            </p>
            <div className="bf-modal-actions">
              <button
                className="bf-btn bf-btn-outline"
                onClick={() => setArchiveConfirm(null)}
              >
                Cancel
              </button>
              <button
                className="bf-btn bf-btn-danger"
                onClick={() => handleArchive(archiveConfirm)}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
