import { useState, useMemo, Fragment } from 'react';
import {
  Search,
  ChevronDown,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  FileText,
  Stethoscope,
  Pill,
  Download,
  XCircle,
  Plus,
  X,
  Save,
  Edit2,
  Trash2,
} from 'lucide-react';
import { format, isWithinInterval, subMonths, parseISO } from 'date-fns';
import { DatePickerInput } from '../components/DatePickerInput';
import { cn } from '../utils/helpers';
import { useHealthStore } from '../store/useHealthStore';
import { useActivePatientId } from '../hooks/useActivePatientId';
import type { APIDiagnosis } from '../services/medical';

interface Disease {
  id: string;
  date: string;
  diagnosisCode: string;
  diagnosisName: string;
  clinic: string;
  physician: string;
  hospital: string;
  severity: 'Mild' | 'Moderate' | 'Severe';
  description?: string;
  clinicalNotes?: string;
  department?: string;
  bodyRegion?: string;
  diseaseDescription?: string;
  symptoms?: string;
  commonTreatments?: string;
  relatedMedications?: {
    name: string;
    dosage: string;
    frequency: string;
  }[];
}

function mapDiagnosis(d: APIDiagnosis): Disease {
  const dateObj = new Date(d.diagnosisDate);
  const dateStr = format(dateObj, "yyyy-MM-dd HH:mm");

  // Use populated disease name, fall back to ICD code
  const diseaseName = d.disease?.name || d.icdCode;

  // Map related prescriptions to medication entries
  const relatedMedications = (d.relatedPrescriptions || [])
    .filter(p => p.medication)
    .map(p => ({
      name: p.medication!.genericName || 'Unknown',
      dosage: p.dosage,
      frequency: p.frequency,
    }));

  return {
    id: d._id,
    date: dateStr,
    diagnosisCode: d.icdCode,
    diagnosisName: diseaseName,
    clinic: d.diagnosisClinic || 'General',
    physician: d.practitioner,
    hospital: d.hospital,
    severity: (d.severity ? d.severity.charAt(0).toUpperCase() + d.severity.slice(1) : 'Mild') as 'Mild' | 'Moderate' | 'Severe',
    description: d.disease?.description || d.notes?.split('.')[0] || undefined,
    clinicalNotes: d.notes || undefined,
    department: d.diagnosisClinic || undefined,
    bodyRegion: d.disease?.bodyRegion || undefined,
    diseaseDescription: d.disease?.description || undefined,
    symptoms: d.disease?.symptoms || undefined,
    commonTreatments: d.disease?.commonTreatments || undefined,
    relatedMedications,
  };
}

type SortField = 'date' | 'diagnosisName' | 'clinic' | 'physician' | 'diagnosisCode';
type SortDirection = 'asc' | 'desc';
type SeverityFilter = 'All' | 'Mild' | 'Moderate' | 'Severe';

export function DiseasesPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [sortField, setSortField] = useState<SortField>('date');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [severityFilter, setSeverityFilter] = useState<SeverityFilter>('All');
  const [activeQuickDate, setActiveQuickDate] = useState<number | null>(null);

  const activePatientId = useActivePatientId();
  const rawDiagnoses = useHealthStore((s) => s._rawDiagnoses);
  const loadedUserId = useHealthStore((s) => s._loadedUserId);
  const diseases = useMemo(() => rawDiagnoses.map(mapDiagnosis), [rawDiagnoses]);
  const isDataLoading = loadedUserId === null;

  const addDiagnosis = useHealthStore(s => s.addDiagnosis);
  const editDiagnosis = useHealthStore(s => s.editDiagnosis);
  const removeDiagnosis = useHealthStore(s => s.removeDiagnosis);

  // Modal/Form States
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [processing, setProcessing] = useState(false);
  const [form, setForm] = useState({
    icdCode: '',
    diagnosisDate: format(new Date(), 'yyyy-MM-dd'),
    severity: 'mild' as 'mild' | 'moderate' | 'severe',
    practitioner: '',
    hospital: '',
    diagnosisClinic: '',
    notes: ''
  });

  const handleQuickDate = (months: number) => {
    const today = new Date();
    const pastDate = subMonths(today, months);
    setEndDate(format(today, 'yyyy-MM-dd'));
    setStartDate(format(pastDate, 'yyyy-MM-dd'));
  };

  const parseDate = (dateStr: string) => {
    return new Date(dateStr.replace(' ', 'T'));
  };

  const handleOpenAdd = () => {
    setEditingId(null);
    setForm({
      icdCode: '',
      diagnosisDate: format(new Date(), 'yyyy-MM-dd'),
      severity: 'mild',
      practitioner: '',
      hospital: '',
      diagnosisClinic: '',
      notes: ''
    });
    setIsModalOpen(true);
  };

  const handleOpenEdit = (d: APIDiagnosis) => {
    setEditingId(d._id);
    setForm({
      icdCode: d.icdCode || '',
      diagnosisDate: d.diagnosisDate ? format(parseISO(d.diagnosisDate), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
      severity: (d.severity || 'mild') as 'mild' | 'moderate' | 'severe',
      practitioner: d.practitioner || '',
      hospital: d.hospital || '',
      diagnosisClinic: d.diagnosisClinic || '',
      notes: d.notes || ''
    });
    setIsModalOpen(true);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm("Are you sure you want to remove this diagnosis?")) return;
    try {
      await removeDiagnosis(id);
    } catch (err) {
      alert("Failed to remove diagnosis");
    }
  };

  const handleSubmit = async () => {
    if (!activePatientId) return;
    if (!form.icdCode || !form.diagnosisDate) {
      alert("Please fill required fields (ICD Code, Diagnosis Date).");
      return;
    }

    setProcessing(true);
    try {
      const payload = {
        patientId: activePatientId,
        icdCode: form.icdCode,
        diagnosisDate: new Date(form.diagnosisDate).toISOString(),
        severity: form.severity,
        practitioner: form.practitioner || undefined,
        hospital: form.hospital || undefined,
        diagnosisClinic: form.diagnosisClinic || undefined,
        notes: form.notes || undefined
      };

      if (editingId) {
        await editDiagnosis(editingId, payload);
      } else {
        await addDiagnosis(payload);
      }
      setIsModalOpen(false);
    } catch (err) {
      console.error("Operation failed", err);
      alert("Operation failed: " + (err as Error).message);
    } finally {
      setProcessing(false);
    }
  };

  const filteredDiseases = useMemo(() => {
    return diseases.filter(d => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch = !searchTerm ||
        d.diagnosisName.toLowerCase().includes(searchLower) ||
        d.diagnosisCode.toLowerCase().includes(searchLower) ||
        d.clinic.toLowerCase().includes(searchLower) ||
        d.physician.toLowerCase().includes(searchLower) ||
        d.bodyRegion?.toLowerCase().includes(searchLower) ||
        (d.relatedMedications || []).some(p =>
          p.name?.toLowerCase().includes(searchLower)
        );

      let matchesDateRange = true;
      if (startDate || endDate) {
        const diseaseDate = parseDate(d.date);
        const start = startDate ? new Date(startDate) : new Date(0);
        const end = endDate ? new Date(endDate) : new Date(9999, 11, 31);
        matchesDateRange = isWithinInterval(diseaseDate, { start, end });
      }

      const matchesSeverity = severityFilter === 'All' || d.severity === severityFilter;

      return matchesSearch && matchesDateRange && matchesSeverity;
    });
  }, [diseases, searchTerm, startDate, endDate, severityFilter]);

  const sortedDiseases = useMemo(() => {
    return [...filteredDiseases].sort((a, b) => {
      let comparison = 0;
      switch (sortField) {
        case 'date':
          comparison = parseDate(a.date).getTime() - parseDate(b.date).getTime();
          break;
        case 'diagnosisName':
          comparison = a.diagnosisName.localeCompare(b.diagnosisName);
          break;
        case 'diagnosisCode':
          comparison = a.diagnosisCode.localeCompare(b.diagnosisCode);
          break;
        case 'clinic':
          comparison = a.clinic.localeCompare(b.clinic);
          break;
        case 'physician':
          comparison = a.physician.localeCompare(b.physician);
          break;
      }
      return sortDirection === 'asc' ? comparison : -comparison;
    });
  }, [filteredDiseases, sortField, sortDirection]);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  };

  const handleExport = () => {
    const headers = ['Date', 'ICD Code', 'Diagnosis Name', 'Severity', 'Clinic', 'Physician', 'Hospital'];
    const csvContent = [
      headers.join(','),
      ...sortedDiseases.map(d => [
        d.date,
        d.diagnosisCode,
        `"${d.diagnosisName}"`,
        d.severity,
        `"${d.clinic}"`,
        `"${d.physician}"`,
        `"${d.hospital}"`
      ].join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    if (link.download !== undefined) {
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', 'diagnoses_history.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const SortButton = ({ field, label }: { field: SortField; label: string }) => (
    <button
      onClick={() => handleSort(field)}
      className="flex items-center gap-1 group text-xs font-semibold text-gray-500 uppercase tracking-wider hover:text-gray-700"
    >
      <span>{label}</span>
      <div className="flex items-center">
        {sortField !== field ? (
          <ArrowUpDown className="w-4 h-4 text-gray-300 group-hover:text-gray-400 transition-colors" />
        ) : sortDirection === 'asc' ? (
          <ArrowUp className="w-4 h-4 text-primary transition-colors" />
        ) : (
          <ArrowDown className="w-4 h-4 text-primary transition-colors" />
        )}
      </div>
    </button>
  );

  if (isDataLoading) {
    return (
      <div className="flex items-center justify-center py-32">
        <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
      </div>
    );
  }

  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">My Diagnoses</h1>
          <p className="text-gray-500 text-sm mt-1">View a comprehensive history of your diagnoses and chronic conditions</p>
        </div>
        <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
          <button
            onClick={handleExport}
            className="inline-flex items-center gap-2 px-4 py-2 bg-[#2DD4BF] text-white rounded-lg hover:bg-[#26b8a6] transition-colors font-medium text-sm shadow-sm"
          >
            <Download className="w-4 h-4" />
            Export Diagnosis History
          </button>
          <button
            onClick={handleOpenAdd}
            className="flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold shadow-lg shadow-primary/25 hover:-translate-y-0.5 active:translate-y-0 transition-all shrink-0"
          >
            <Plus className="w-4 h-4" />
            <span>Add Diagnosis</span>
          </button>
        </div>
      </div>

      {/* Filters Bar */}
      <div className="mb-8">
        <div className="flex flex-col xl:flex-row gap-4 items-center">
          {/* Search (Left) */}
          <div className="relative w-full xl:w-1/4">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
            <input
              type="text"
              placeholder="Search by diagnosis, department, prescription..."
              className="pl-10 pr-4 py-2.5 w-full bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* Date & Quick Select Wrapper */}
          <div className="flex flex-col lg:flex-row items-center gap-4 w-full xl:w-auto xl:ml-auto">
            <div className="flex flex-col sm:flex-row items-center justify-center gap-2 w-full sm:w-auto h-full">
              <div className="flex items-center gap-2 h-full w-full sm:w-auto">
                {(startDate || endDate) && (
                  <button
                    onClick={() => { setStartDate(''); setEndDate(''); setActiveQuickDate(null); }}
                    className="p-2 text-gray-400 hover:text-red-500 transition-all flex items-center shrink-0"
                  >
                    <XCircle className="w-5 h-5" />
                  </button>
                )}
                <div className="relative flex items-center h-full flex-1 sm:w-auto">
                  <DatePickerInput
                    value={startDate}
                    onChange={(e) => { setStartDate(e); setActiveQuickDate(null); }}
                    placeholder="Start date"
                    className="w-full sm:min-w-[140px] text-gray-600"
                  />
                </div>
              </div>
              <span className="hidden sm:flex items-center justify-center text-gray-400 h-10 px-1 shrink-0">-</span>
              <div className="relative flex items-center h-full w-full sm:w-auto">
                <DatePickerInput
                  value={endDate}
                  onChange={(e) => { setEndDate(e); setActiveQuickDate(null); }}
                  placeholder="End date"
                  className="w-full sm:min-w-[140px] text-gray-600"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-3 gap-1.5 w-full sm:w-auto items-center">
              {[
                { label: 'Last 1 Month', val: 1 },
                { label: 'Last 3 Months', val: 3 },
                { label: 'Last 6 Months', val: 6 },
                { label: 'Last 1 Year', val: 12 },
                { label: 'Last 2 Years', val: 24 },
                { label: 'Last 5 Years', val: 60 },
              ].map((btn) => {
                const isActive = activeQuickDate === btn.val;
                return (
                  <button
                    key={btn.label}
                    onClick={() => { handleQuickDate(btn.val); setActiveQuickDate(btn.val); }}
                    className={cn(
                      "px-2 py-1.5 text-[10px] font-bold uppercase tracking-tight border rounded transition-all whitespace-nowrap text-center flex items-center justify-center",
                      isActive
                        ? "bg-blue-500 text-white border-blue-600 shadow-sm"
                        : "text-gray-500 bg-gray-50 border-gray-200 hover:bg-primary/5 hover:text-primary"
                    )}
                  >
                    {btn.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Severity Filter (Right) */}
          <div className="flex bg-gray-100/80 p-1 rounded-lg items-center">
            {(['All', 'Mild', 'Moderate', 'Severe'] as SeverityFilter[]).map((severity) => (
              <button
                key={severity}
                onClick={() => setSeverityFilter(severity)}
                className={cn(
                  "px-4 py-1.5 text-sm font-medium rounded-md transition-all",
                  severityFilter === severity ? "bg-white text-gray-900 shadow-sm" : "text-gray-300"
                )}
              >
                {severity}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Data Table */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden ring-1 ring-black/[0.02]">
        <table className="w-full text-left table-fixed">
          <thead className="bg-gray-50/50 border-b border-gray-100">
            <tr>
              <th className="px-6 py-4 w-[180px]">
                <SortButton field="date" label="Date" />
              </th>
              <th className="px-6 py-4 w-[15%]">
                <SortButton field="diagnosisCode" label="ICD Code" />
              </th>
              <th className="px-6 py-4 w-[30%]">
                <SortButton field="diagnosisName" label="Diagnosis" />
              </th>
              <th className="px-6 py-4 w-[18%]">
                <SortButton field="clinic" label="Department" />
              </th>
              <th className="px-6 py-4 w-[18%]">
                <SortButton field="physician" label="Attending Doctor" />
              </th>
              <th className="px-6 py-4 w-[80px]" />
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {sortedDiseases.map((disease) => {
              const diseaseDate = new Date(disease.date.replace(' ', 'T'));
              const displayDate = format(diseaseDate, 'MMM d, yyyy');
              const isExpanded = expandedId === disease.id;
              const rawDiag = rawDiagnoses.find(rd => rd._id === disease.id);

              return (
                <Fragment key={disease.id}>
                  <tr
                    className={cn(
                      "hover:bg-gray-50/50 transition-all cursor-pointer group bg-white",
                      isExpanded && "bg-primary/[0.02]"
                    )}
                    onClick={() => setExpandedId(isExpanded ? null : disease.id)}
                  >
                    <td className="px-6 py-5 align-top">
                      <div className="text-sm font-bold text-gray-900">{displayDate}</div>
                      <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mt-1">{format(diseaseDate, 'EEEE')}</div>
                    </td>
                    <td className="px-6 py-5 align-top">
                      <span className="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-bold font-mono bg-cyan-50 text-cyan-700 border border-cyan-100">
                        {disease.diagnosisCode}
                      </span>
                    </td>
                    <td className="px-6 py-5 align-top">
                      <div className="flex items-center gap-2">
                        <div className={cn(
                          "w-1.5 h-1.5 rounded-full shrink-0",
                          disease.severity === 'Mild' ? 'bg-emerald-400' :
                          disease.severity === 'Moderate' ? 'bg-amber-400' : 'bg-red-500'
                        )} />
                        <span className="text-sm font-bold text-gray-900 leading-snug">{disease.diagnosisName}</span>
                      </div>
                      <p className="text-[11px] font-medium text-gray-400 mt-1 line-clamp-1">{disease.description || 'No description available'}</p>
                    </td>
                    <td className="px-6 py-5 align-top">
                      <span className="text-sm font-semibold text-gray-700">{disease.clinic}</span>
                    </td>
                    <td className="px-6 py-5 align-top">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-[11px] font-bold text-primary border border-primary/20 shrink-0">
                          {disease.physician.split(' ').slice(-1)[0][0] || 'DR'}
                        </div>
                        <div className="min-w-0">
                          <span className="text-sm text-gray-700 font-bold block truncate">Dr. {disease.physician.replace(/^Dr\.?\s*/i, '')}</span>
                          <span className="text-[10px] text-gray-400 font-bold uppercase tracking-tighter truncate">{disease.hospital || 'Facility'}</span>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-5 text-right align-top">
                      <div className="flex items-center justify-end gap-1">
                        <div className="flex items-center gap-1">
                          <button
                            onClick={(e) => { e.stopPropagation(); if (rawDiag) handleOpenEdit(rawDiag); }}
                            className="p-1.5 text-gray-400 hover:text-primary hover:bg-primary/5 rounded-lg transition-all"
                            title="Edit Diagnosis"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={(e) => { e.stopPropagation(); handleDelete(disease.id); }}
                            className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                            title="Remove Record"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                        <button
                          className={cn(
                            "w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300",
                            isExpanded ? "bg-primary/10 text-primary rotate-180" : "text-gray-400 hover:bg-ray-100"
                          )}
                        >
                          <ChevronDown className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>

                  {isExpanded && (
                    <tr className="bg-gray-50/50">
                      <td colSpan={6} className="px-6 py-8 border-t border-gray-100">
                        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 animate-in fade-in slide-in-from-top-2 duration-300">
                          {/* Column 1: Clinical Details */}
                          <div className="bg-white rounded-2xl border border-gray-200 p-6 shadow-sm ring-1 ring-black/[0.02]">
                            <div className="flex items-center gap-2.5 mb-6">
                              <div className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center">
                                <FileText className="w-4 h-4 text-gray-500" />
                              </div>
                              <h4 className="text-xs font-bold text-gray-900 uppercase tracking-widest">Clinical Details</h4>
                            </div>
                            <div className="space-y-5">
                              <div>
                                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Medical Description</span>
                                <p className="text-sm text-gray-900 font-bold leading-snug">{disease.diseaseDescription || disease.description || disease.diagnosisName}</p>
                              </div>
                              <div className="grid grid-cols-2 gap-4">
                                <div>
                                  <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Body Region</span>
                                  <p className="text-sm text-gray-900 font-bold capitalize">{disease.bodyRegion || 'General'}</p>
                                </div>
                                <div>
                                  <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Severity</span>
                                  <div className="flex items-center gap-2 mt-0.5">
                                    <div className={cn(
                                      "w-2 h-2 rounded-full",
                                      disease.severity === 'Mild' ? 'bg-emerald-500' :
                                      disease.severity === 'Moderate' ? 'bg-amber-500' : 'bg-red-500'
                                    )} />
                                    <span className="text-sm text-gray-900 font-bold">{disease.severity}</span>
                                  </div>
                                </div>
                              </div>
                              {disease.symptoms && (
                                <div className="pt-4 border-t border-gray-50">
                                  <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-2">Common Symptoms</span>
                                  <p className="text-xs text-gray-600 leading-relaxed font-medium">{disease.symptoms}</p>
                                </div>
                              )}
                              {disease.commonTreatments && (
                                <div className="pt-4 border-t border-gray-50">
                                  <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-2">Common Treatments</span>
                                  <p className="text-xs text-gray-600 leading-relaxed font-medium">{disease.commonTreatments}</p>
                                </div>
                              )}
                            </div>
                          </div>

                          {/* Column 2: Provider Information */}
                          <div className="bg-white rounded-2xl border border-gray-200 p-6 shadow-sm ring-1 ring-black/[0.02]">
                            <div className="flex items-center gap-2.5 mb-6">
                              <div className="w-8 h-8 rounded-lg bg-cyan-50 flex items-center justify-center">
                                <Stethoscope className="w-4 h-4 text-cyan-600" />
                              </div>
                              <h4 className="text-xs font-bold text-gray-900 uppercase tracking-widest">Provider Information</h4>
                            </div>
                            <div className="space-y-5">
                              <div>
                                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Diagnosing Physician</span>
                                <p className="text-sm font-bold">Dr. {disease.physician.replace(/^Dr\.?\s*/i, '')}</p>
                              </div>
                              <div>
                                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Hospital • Department</span>
                                <p className="text-sm font-bold leading-tight">
                                  {disease.hospital || 'Medical Center'} • {disease.department || disease.clinic}
                                </p>
                              </div>
                              <div>
                                <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-1">Diagnosis Date</span>
                                <p className="text-sm font-bold">{format(diseaseDate, 'MMMM do, yyyy')}</p>
                              </div>
                              {disease.clinicalNotes && (
                                <div className="pt-4 border-t border-gray-50">
                                  <span className="text-[10px] font-bold text-gray-400 uppercase tracking-wider block mb-2">Clinical Notes</span>
                                  <div className="bg-gray-50/50 rounded-xl p-4 border border-gray-100">
                                    <p className="text-xs text-gray-600 leading-relaxed italic font-medium">"{disease.clinicalNotes}"</p>
                                  </div>
                                </div>
                              )}
                            </div>
                          </div>

                          {/* Column 3: Related Medications */}
                          <div className="bg-white rounded-2xl border border-gray-200 p-6 shadow-sm ring-1 ring-black/[0.02]">
                            <div className="flex items-center gap-2.5 mb-6">
                              <div className="w-8 h-8 rounded-lg bg-violet-50 flex items-center justify-center">
                                <Pill className="w-4 h-4 text-violet-600" />
                              </div>
                              <h4 className="text-xs font-bold text-gray-900 uppercase tracking-widest">Linked Medications</h4>
                            </div>
                            {disease.relatedMedications && disease.relatedMedications.length > 0 ? (
                              <div className="space-y-3">
                                {disease.relatedMedications.map((med, idx) => (
                                  <div key={idx} className="group p-4 bg-violet-50/30 hover:bg-violet-50 rounded-xl border border-violet-100/50 transition-all">
                                    <div className="flex items-center gap-4">
                                      <div className="w-10 h-10 rounded-xl bg-white shadow-sm flex items-center justify-center text-violet-600 shrink-0 border border-violet-100">
                                        <Pill className="w-5 h-5" />
                                      </div>
                                      <div className="min-w-0">
                                        <p className="text-sm font-bold text-gray-900 truncate">{med.name}</p>
                                        {(med.dosage || med.frequency) && (
                                          <p className="text-[11px] text-violet-600 font-bold mt-1">
                                            {[med.dosage, med.frequency].filter(Boolean).join(' • ')}
                                          </p>
                                        )}
                                      </div>
                                    </div>
                                  </div>
                                ))}
                              </div>
                            ) : (
                              <div className="h-40 bg-gray-50/50 rounded-2xl border border-gray-100 border-dashed flex flex-col items-center justify-center text-center px-4">
                                <Pill className="w-8 h-8 text-gray-200 mb-2" />
                                <p className="text-[11px] font-bold text-gray-400 uppercase tracking-wider">No Medications Linked</p>
                              </div>
                            )}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </Fragment>
              );
            })}
          </tbody>
        </table>

        {sortedDiseases.length === 0 && (
          <div className="flex flex-col items-center justify-center py-24 px-4">
            <div className="w-20 h-20 rounded-full bg-gray-50 flex items-center justify-center mb-6 ring-1 ring-black/[0.02]">
              <Search className="w-10 h-10 text-gray-200" />
            </div>
            <h3 className="text-xl font-bold text-gray-900 mb-2">No diagnoses found</h3>
            <p className="text-sm text-gray-400 text-center max-w-sm font-medium">
              We couldn't find any medical records matching your current filters. Try resetting your search or date range.
            </p>
          </div>
        )}
      </div>

      {/* Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/60 z-[100] backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="p-4 border-b flex justify-between items-center bg-gray-50">
              <h3 className="font-bold text-gray-900">{editingId ? 'Edit Diagnosis' : 'Add New Diagnosis'}</h3>
              <button onClick={() => setIsModalOpen(false)} className="p-1 hover:bg-gray-200 rounded-md">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <div className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
              <div className="grid grid-cols-2 gap-4">
                <div className="col-span-2">
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">ICD Code *</label>
                  <input
                    type="text"
                    value={form.icdCode}
                    onChange={e => setForm({ ...form, icdCode: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20"
                    placeholder="e.g. J01.90"
                  />
                </div>

                <div className="col-span-2">
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Diagnosis Date *</label>
                  <DatePickerInput value={form.diagnosisDate} onChange={val => setForm({ ...form, diagnosisDate: val })} className="w-full" />
                </div>

                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Severity</label>
                  <select
                    value={form.severity}
                    onChange={e => setForm({ ...form, severity: e.target.value as any })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20 bg-white"
                  >
                    <option value="mild">Mild</option>
                    <option value="moderate">Moderate</option>
                    <option value="severe">Severe</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Department / Clinic</label>
                  <input
                    type="text"
                    value={form.diagnosisClinic}
                    onChange={e => setForm({ ...form, diagnosisClinic: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20"
                    placeholder="e.g. Otolaryngology"
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Doctor Name</label>
                  <input
                    type="text"
                    value={form.practitioner}
                    onChange={e => setForm({ ...form, practitioner: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20"
                    placeholder="e.g. Dr. John Doe"
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Hospital</label>
                  <input
                    type="text"
                    value={form.hospital}
                    onChange={e => setForm({ ...form, hospital: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20"
                    placeholder="e.g. City General"
                  />
                </div>

                <div className="col-span-2">
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Clinical Notes</label>
                  <textarea
                    value={form.notes}
                    onChange={e => setForm({ ...form, notes: e.target.value })}
                    className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20 min-h-[100px]"
                    placeholder="Enter diagnosis details or notes..."
                  />
                </div>
              </div>

              <button
                onClick={handleSubmit}
                disabled={processing}
                className="w-full flex items-center justify-center gap-2 bg-primary text-white py-2.5 rounded-lg font-bold shadow-md hover:bg-primary/90 mt-2 transition-all disabled:opacity-50"
              >
                {processing ? <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="w-4 h-4" />}
                {processing ? 'Processing...' : editingId ? 'Update Diagnosis' : 'Save Diagnosis'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

