import React, { useEffect, useRef } from 'react';
import { HistoricalDose } from '../../types';
import {
  PillIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
} from '../icons/Icons';

interface HistoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  history: { date: string; doses: HistoricalDose[] }[];
}

const getStatusIcon = (status: HistoricalDose['status']) => {
  switch (status) {
    case 'TAKEN':
      return (
        <CheckCircleIcon className='w-5 h-5 text-green-500 dark:text-green-400' />
      );
    case 'MISSED':
      return <XCircleIcon className='w-5 h-5 text-red-500 dark:text-red-400' />;
    default:
      return (
        <ClockIcon className='w-5 h-5 text-slate-400 dark:text-slate-500' />
      );
  }
};

const HistoryModal: React.FC<HistoryModalProps> = ({
  isOpen,
  onClose,
  history,
}) => {
  const modalRef = useRef<HTMLDivElement>(null);
  const closeButtonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (isOpen) {
      setTimeout(() => closeButtonRef.current?.focus(), 100);
    }
  }, [isOpen]);

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown);
    }
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  useEffect(() => {
    if (!isOpen || !modalRef.current) return;
    const focusableElements = modalRef.current.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    const firstElement = focusableElements[0] as HTMLElement;
    const lastElement = focusableElements[
      focusableElements.length - 1
    ] as HTMLElement;

    const handleTabKey = (e: KeyboardEvent) => {
      if (e.key !== 'Tab') return;
      if (e.shiftKey) {
        if (document.activeElement === firstElement) {
          lastElement.focus();
          e.preventDefault();
        }
      } else {
        if (document.activeElement === lastElement) {
          firstElement.focus();
          e.preventDefault();
        }
      }
    };

    document.addEventListener('keydown', handleTabKey);
    return () => document.removeEventListener('keydown', handleTabKey);
  }, [isOpen]);

  if (!isOpen) return null;

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const userTimezoneOffset = date.getTimezoneOffset() * 60000;
    return new Date(date.getTime() + userTimezoneOffset).toLocaleDateString(
      undefined,
      {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      }
    );
  };

  return (
    <div
      className='fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 z-50 flex justify-center items-center p-4'
      role='dialog'
      aria-modal='true'
      aria-labelledby='history-title'
    >
      <div
        className='bg-white dark:bg-slate-800 rounded-lg shadow-xl w-full max-w-2xl'
        ref={modalRef}
      >
        <div className='p-6 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center'>
          <h3
            id='history-title'
            className='text-xl font-semibold text-slate-800 dark:text-slate-100'
          >
            Medication History
          </h3>
          <button
            onClick={onClose}
            ref={closeButtonRef}
            className='text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 text-3xl leading-none'
            aria-label='Close'
          >
            &times;
          </button>
        </div>
        <div className='p-6 max-h-[60vh] overflow-y-auto space-y-6'>
          {history.length > 0 ? (
            history.map(({ date, doses }) => (
              <section key={date}>
                <h4 className='font-bold text-slate-700 dark:text-slate-300 mb-3'>
                  {formatDate(date)}
                </h4>
                <ul className='space-y-2'>
                  {doses.map(dose => (
                    <li
                      key={dose.id}
                      className='p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg flex justify-between items-center'
                    >
                      <div className='flex items-center space-x-3'>
                        <div className='flex-shrink-0'>
                          {getStatusIcon(dose.status)}
                        </div>
                        <div>
                          <p className='font-semibold text-slate-800 dark:text-slate-100'>
                            {dose.medication.name}
                          </p>
                          <p className='text-sm text-slate-500 dark:text-slate-400'>
                            {dose.medication.dosage}
                          </p>
                        </div>
                      </div>
                      <div className='text-right'>
                        <p className='font-medium text-slate-700 dark:text-slate-300'>
                          {dose.scheduledTime.toLocaleTimeString([], {
                            hour: '2-digit',
                            minute: '2-digit',
                          })}
                        </p>
                        {dose.status === 'TAKEN' && dose.takenAt && (
                          <p className='text-xs text-green-600 dark:text-green-500'>
                            Taken at{' '}
                            {new Date(dose.takenAt).toLocaleTimeString([], {
                              hour: '2-digit',
                              minute: '2-digit',
                            })}
                          </p>
                        )}
                        {dose.status === 'MISSED' && (
                          <p className='text-xs text-red-600 dark:text-red-500'>
                            Missed
                          </p>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              </section>
            ))
          ) : (
            <div className='text-center py-10'>
              <PillIcon className='w-12 h-12 mx-auto text-slate-300 dark:text-slate-600' />
              <p className='mt-4 text-slate-500 dark:text-slate-400'>
                No medication history found.
              </p>
              <p className='text-sm text-slate-400 dark:text-slate-500'>
                History will appear here once you start tracking doses.
              </p>
            </div>
          )}
        </div>
        <div className='px-6 py-4 bg-slate-50 dark:bg-slate-700/50 flex justify-end rounded-b-lg border-t border-slate-200 dark:border-slate-700'>
          <button
            type='button'
            onClick={onClose}
            className='px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-md shadow-sm hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:bg-slate-700 dark:text-slate-200 dark:border-slate-600 dark:hover:bg-slate-600 dark:focus:ring-offset-slate-800'
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
};

export default HistoryModal;
