import React, { useMemo } from 'react';
import { format, parseISO } from 'date-fns';
import { Calendar, Pill, ArrowRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { PopoverClose } from './ui/popover';
import { useHealthStore } from '../store/useHealthStore';
import { cn } from '../utils/helpers';
import { formatSpecificTime } from '../utils/eventTime';
import type { Medication, Appointment, LabResult, ImagingEvent } from '../types/medical';
import { 
  ICON_MAP, 
  COLOR_MAP, 
  getTimelineTitle, 
  getTimelineSubtext, 
  formatOptionalDate, 
  countDaysFrom, 
  countInclusiveDays, 
  isPrescriptionActive, 
  findLinkedDiagnosisForPrescription,
  type DisplayedTimelineEvent 
} from './Timeline';

export function GroupedEventsPopoverContent({ events }: { events: DisplayedTimelineEvent[] }) {
  const sortedEvents = events.slice().sort((a, b) => {
    const aTime = 'time' in a && a.time ? a.time : '00:00';
    const bTime = 'time' in b && b.time ? b.time : '00:00';
    return `${a.date}-${aTime}`.localeCompare(`${b.date}-${bTime}`);
  });

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h3 className="text-base font-bold text-slate-900">{sortedEvents.length} events on this date</h3>
          <p className="text-xs text-slate-500">Zoom in to separate them into individual timeline nodes.</p>
        </div>
        <PopoverClose className="p-1 rounded-full hover:bg-slate-100 text-slate-400 transition-colors">
          <span className="sr-only">Close</span>
          ✕
        </PopoverClose>
      </div>

      <div className="space-y-2">
        {sortedEvents.map((event) => {
          const Icon = ICON_MAP[event.type];
          const colorClass = COLOR_MAP[event.type];

          return (
            <div key={event.id} className="flex items-start gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5">
              <div className={cn("flex h-10 w-10 shrink-0 items-center justify-center rounded-xl", colorClass.split(' ')[0])}>
                {React.createElement(Icon, { size: 18, className: colorClass.split(' ')[1] })}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center justify-between gap-3">
                  <span className="truncate text-sm font-semibold text-slate-900">{getTimelineTitle(event)}</span>
                  <span className="shrink-0 text-xs text-slate-400">
                    {('time' in event && formatSpecificTime(event.time)) || format(parseISO(event.date), "MMM d")}
                  </span>
                </div>
                <p className="mt-0.5 truncate text-xs text-slate-500">{getTimelineSubtext(event)}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export function EventPopoverContent({ event, onClose }: { event: DisplayedTimelineEvent; onClose?: () => void }) {
  const Icon = ICON_MAP[event.type];
  const colorClass = COLOR_MAP[event.type];
  const navigate = useNavigate();
  const rawPrescriptions = useHealthStore((state) => state._rawPrescriptions);
  const rawDiagnoses = useHealthStore((state) => state._rawDiagnoses);
  
  const medicationDetails = useMemo(() => {
    if (event.type !== 'prescriptions') return null;

    const medicationEvent = event as Medication;
    const prescription = rawPrescriptions.find((entry) => entry._id === event.id || entry.prescriptionId === event.id) || null;
    const linkedDiagnosis = findLinkedDiagnosisForPrescription(prescription, rawDiagnoses);
    const activeStart = prescription?.startDate || medicationEvent.startDate || medicationEvent.date;
    const prescribedAt = prescription?.prescribedDate || activeStart;
    const activeEnd = prescription?.endDate || medicationEvent.endDate;

    const now = Date.now();
    const prescribedDateObj = parseISO(prescribedAt);
    const startObj = parseISO(activeStart);
    const prescribedIsFuture = !Number.isNaN(prescribedDateObj.getTime()) && prescribedDateObj.getTime() > now;
    const startIsFuture = !Number.isNaN(startObj.getTime()) && startObj.getTime() > now;
    const daysSince = countDaysFrom(prescribedAt);
    
    let prescribedText = "Prescribed";
    if (prescribedIsFuture || startIsFuture) {
      prescribedText = "Prescribed (Future)";
    } else if (daysSince === 0) {
      prescribedText = "Prescribed today";
    } else if (daysSince !== null) {
      prescribedText = `Prescribed ${daysSince} days ago`;
    }

    return {
      activeEnd,
      activeStart,
      daysSincePrescribed: daysSince,
      prescribedText,
      diagnosisName: linkedDiagnosis?.disease?.name || null,
      dosage: prescription?.dosage || medicationEvent.dosage,
      frequency: prescription?.frequency || medicationEvent.frequency,
      instructions: prescription?.instructions || medicationEvent.instructions || medicationEvent.indication,
      isActive: isPrescriptionActive(prescription, medicationEvent.endDate),
      prescribedBy: prescription?.doctorName?.trim() || null,
      prescriptionId: prescription?._id || medicationEvent.id,
      treatmentDays: countInclusiveDays(activeStart, activeEnd),
    };
  }, [event, rawDiagnoses, rawPrescriptions]);

  const activeDisplayDate = medicationDetails?.activeStart || event.date;
  const displayTime = 'time' in event ? formatSpecificTime(event.time) : '';
  const navigationTarget = (() => {
    if (event.type === 'prescriptions') {
      return {
        label: 'Open prescription',
        path: medicationDetails?.prescriptionId ? `/prescriptions/${medicationDetails.prescriptionId}` : '/prescriptions',
      };
    }
    if (event.type === 'vaccinations') return { label: 'Open vaccinations', path: '/vaccinations' };
    if (event.type === 'labs') return { label: 'Open blood tests', path: '/tests' };
    if (event.type === 'imaging') return { label: 'Open imaging', path: '/images' };
    return { label: 'Open visit', path: '/visits' };
  })();

  const CloseButton = onClose ? (
    <button onClick={onClose} className="p-1 rounded-full hover:bg-slate-100 text-slate-400 transition-colors focus:outline-none">
       <span className="sr-only">Close</span>✕
    </button>
  ) : (
    <PopoverClose className="p-1 rounded-full hover:bg-slate-100 text-slate-400 transition-colors focus:outline-none">
      <span className="sr-only">Close</span>✕
    </PopoverClose>
  );

  const OpenButton = (
    <button
      type="button"
      onClick={() => {
        onClose?.();
        navigate(navigationTarget.path);
      }}
      className="flex w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm font-semibold text-slate-700 shadow-sm transition hover:border-slate-300 hover:bg-slate-50"
    >
      {navigationTarget.label}
      <ArrowRight size={14} />
    </button>
  );

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className={cn("p-2.5 rounded-xl", colorClass.split(' ')[0])}>
            {React.createElement(Icon, { size: 20, className: colorClass.split(' ')[1] })}
          </div>
          <div>
            <h3 className="text-base font-bold text-slate-900">{getTimelineTitle(event)}</h3>
            <p className="text-xs text-slate-500 capitalize">{event.type}</p>
          </div>
        </div>
        {CloseButton}
      </div>

      <div className="flex items-center gap-2 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 text-sm text-slate-600">
        <Calendar size={14} className="shrink-0 text-slate-400" />
        <span>{format(parseISO(activeDisplayDate), "EEEE, MMMM do")}</span>
        {displayTime && (
          <span className="text-slate-400">at {displayTime}</span>
        )}
      </div>

      {event.type === 'prescriptions' && medicationDetails && (
        <div className="space-y-2">
          <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-3">
            <div className="mb-1 flex items-center justify-between gap-3">
              <div className="flex items-center gap-2">
                <Pill size={14} className="text-emerald-600" />
                <span className="text-sm font-semibold text-emerald-900">{medicationDetails.prescribedText}</span>
              </div>
              <span className={cn(
                "rounded-full border px-2 py-0.5 text-[11px] font-semibold",
                medicationDetails.isActive
                  ? "border-emerald-200 bg-white/80 text-emerald-700"
                  : "border-slate-200 bg-white/80 text-slate-600"
              )}>
                {medicationDetails.isActive ? "Active" : "Ended"}
              </span>
            </div>
            <p className="mt-2 text-xs text-emerald-700">
              {formatOptionalDate(medicationDetails.activeStart)} → {formatOptionalDate(medicationDetails.activeEnd)}
              {medicationDetails.treatmentDays ? ` · ${medicationDetails.treatmentDays} day course` : ''}
            </p>
          </div>

          <div className="grid grid-cols-2 gap-2">
            <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
              <span className="mb-0.5 block text-xs text-slate-400">Dosage</span>
              <span className="text-sm font-medium text-slate-900">{medicationDetails.dosage}</span>
            </div>
            <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
              <span className="mb-0.5 block text-xs text-slate-400">Frequency</span>
              <span className="text-sm font-medium text-slate-900">{medicationDetails.frequency}</span>
            </div>
            {medicationDetails.prescribedBy && (
              <div className="col-span-2 rounded-xl border border-slate-100 bg-slate-50 p-3">
                <span className="mb-0.5 block text-xs text-slate-400">Prescribed by</span>
                <span className="text-sm font-medium text-slate-900">{medicationDetails.prescribedBy}</span>
              </div>
            )}
          </div>

          {medicationDetails.diagnosisName && (
            <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
              <span className="mb-0.5 block text-xs text-slate-400">Diagnosis</span>
              <span className="text-sm font-medium text-slate-900">{medicationDetails.diagnosisName}</span>
            </div>
          )}

          {medicationDetails.instructions && (
            <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
              <span className="mb-0.5 block text-xs text-slate-400">Instructions</span>
              <span className="text-sm leading-relaxed text-slate-700">{medicationDetails.instructions}</span>
            </div>
          )}
        </div>
      )}

      {event.type === 'appointments' && (() => {
        const apt = event as Appointment;
        return (
          <div className="space-y-2">
            <div className="grid grid-cols-2 gap-2">
              <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
                <span className="mb-0.5 block text-xs text-slate-400">Doctor</span>
                <span className="text-sm font-medium text-slate-900">{apt.doctor}</span>
              </div>
              <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
                <span className="mb-0.5 block text-xs text-slate-400">Department</span>
                <span className="text-sm font-medium text-slate-900">{apt.specialty}</span>
              </div>
            </div>
            {apt.diagnosis && (
              <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
                <div className="flex items-center justify-between">
                  <span className="mb-0.5 block text-xs text-slate-400">Diagnosis</span>
                  {apt.severity && (
                    <span className={cn(
                      "text-[10px] font-semibold px-2 py-0.5 rounded-md capitalize",
                      apt.severity === 'severe' ? 'bg-red-100 text-red-700' :
                      apt.severity === 'moderate' ? 'bg-orange-100 text-orange-700' :
                      'bg-emerald-100 text-emerald-700'
                    )}>
                      {apt.severity}
                    </span>
                  )}
                </div>
                <span className="text-sm font-medium text-slate-900">{apt.diagnosis}</span>
              </div>
            )}
            {apt.treatment && apt.treatment !== 'Hospital Visit' && (
              <div className="rounded-xl border border-blue-100 bg-blue-50 p-3">
                <span className="mb-0.5 block text-xs text-blue-400">Prescribed Medications</span>
                <span className="text-sm font-medium text-blue-900">{apt.treatment}</span>
              </div>
            )}
            {apt.notes && (
              <div className="text-sm leading-relaxed text-slate-600 bg-slate-50 border border-slate-100 p-3 rounded-xl">
                <span className="mb-1 block font-semibold text-slate-900">Notes</span>
                {apt.notes}
              </div>
            )}
          </div>
        );
      })()}

      {event.type === 'labs' && (
        <div className="text-sm leading-relaxed text-slate-600 bg-slate-50 border border-slate-100 p-3 rounded-xl">
          <span className="mb-1 block text-xs font-semibold text-slate-400 uppercase tracking-wider">Ordering Physician</span>
          <span className="font-medium text-slate-900">{(event as LabResult).orderingPhysician}</span>
        </div>
      )}

      {event.type === 'imaging' && (
        <div className="space-y-2">
          <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
            <span className="mb-0.5 block text-xs text-slate-400">Hospital</span>
            <span className="text-sm font-medium text-slate-900">{(event as ImagingEvent).hospital}</span>
          </div>

          {(event as ImagingEvent).explanation && (
            <div className="rounded-xl border border-slate-100 bg-slate-50 p-3">
              <span className="mb-0.5 block text-xs text-slate-400">Explanation</span>
              <span className="text-sm leading-relaxed text-slate-700">{(event as ImagingEvent).explanation}</span>
            </div>
          )}
        </div>
      )}
      
      {event.type === 'vaccinations' && (
        <div className="text-sm leading-relaxed text-slate-600 bg-slate-50 border border-slate-100 p-3 rounded-xl">
           <span className="mb-1 block text-xs font-semibold text-slate-400 uppercase tracking-wider">Administered At</span>
           <span className="font-medium text-slate-900">{(event as import('../types/medical').VaccinationEvent).administrationPlace}</span>
        </div>
      )}

      {onClose ? (
        OpenButton
      ) : (
        <PopoverClose asChild>
          {OpenButton}
        </PopoverClose>
      )}
    </div>
  );
}
