import React, { useEffect, useRef } from 'react';
import { DailyStat, MedicationStat } from '../../types';
import BarChart from '../ui/BarChart';
import { BarChartIcon, getMedicationIcon } from '../icons/Icons';

interface StatsModalProps {
  isOpen: boolean;
  onClose: () => void;
  dailyStats: DailyStat[];
  medicationStats: MedicationStat[];
}

const formatLastTaken = (isoString?: string) => {
  if (!isoString)
    return <span className='text-slate-400 dark:text-slate-500'>N/A</span>;

  const date = new Date(isoString);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() - 1
  );

  const timeString = date.toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit',
  });
  const datePart = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate()
  );

  if (datePart.getTime() === today.getTime()) {
    return `Today at ${timeString}`;
  }
  if (datePart.getTime() === yesterday.getTime()) {
    return `Yesterday at ${timeString}`;
  }
  return date.toLocaleDateString();
};

const StatsModal: React.FC<StatsModalProps> = ({
  isOpen,
  onClose,
  dailyStats,
  medicationStats,
}) => {
  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]);

  if (!isOpen) return null;

  const hasData = medicationStats.length > 0;

  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='stats-title'
    >
      <div
        className='bg-white dark:bg-slate-800 rounded-lg shadow-xl w-full max-w-3xl'
        ref={modalRef}
      >
        <div className='p-6 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center'>
          <h3
            id='stats-title'
            className='text-xl font-semibold text-slate-800 dark:text-slate-100'
          >
            Medication Statistics
          </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-[70vh] overflow-y-auto space-y-8'>
          {hasData ? (
            <>
              <section>
                <h4 className='text-lg font-semibold text-slate-700 dark:text-slate-200 mb-4'>
                  Weekly Adherence
                </h4>
                <div className='p-4 bg-slate-50 dark:bg-slate-700/50 rounded-lg'>
                  <BarChart data={dailyStats} />
                </div>
              </section>
              <section>
                <h4 className='text-lg font-semibold text-slate-700 dark:text-slate-200 mb-4'>
                  Medication Breakdown
                </h4>
                <div className='overflow-x-auto'>
                  <table className='min-w-full divide-y divide-slate-200 dark:divide-slate-700'>
                    <thead className='bg-slate-50 dark:bg-slate-700/50'>
                      <tr>
                        <th
                          scope='col'
                          className='px-4 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Medication
                        </th>
                        <th
                          scope='col'
                          className='px-4 py-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Taken
                        </th>
                        <th
                          scope='col'
                          className='px-4 py-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Missed
                        </th>
                        <th
                          scope='col'
                          className='px-4 py-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Upcoming
                        </th>
                        <th
                          scope='col'
                          className='px-4 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Last Taken
                        </th>
                        <th
                          scope='col'
                          className='px-4 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider'
                        >
                          Adherence
                        </th>
                      </tr>
                    </thead>
                    <tbody className='bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700'>
                      {medicationStats.map(
                        ({
                          medication,
                          taken,
                          missed,
                          upcoming,
                          adherence,
                          lastTakenAt,
                        }) => {
                          const MedicationIcon = getMedicationIcon(
                            medication.icon
                          );
                          const adherenceColor =
                            adherence >= 90
                              ? 'text-green-600 dark:text-green-400'
                              : adherence >= 70
                                ? 'text-amber-600 dark:text-amber-400'
                                : 'text-red-600 dark:text-red-400';
                          return (
                            <tr key={medication._id}>
                              <td className='px-4 py-4 whitespace-nowrap'>
                                <div className='flex items-center space-x-3'>
                                  <MedicationIcon className='w-6 h-6 text-indigo-500 dark:text-indigo-400 flex-shrink-0' />
                                  <div>
                                    <div className='text-sm font-semibold text-slate-900 dark:text-slate-100'>
                                      {medication.name}
                                    </div>
                                    <div className='text-xs text-slate-500 dark:text-slate-400'>
                                      {medication.dosage}
                                    </div>
                                  </div>
                                </div>
                              </td>
                              <td className='px-4 py-4 whitespace-nowrap text-center text-sm text-slate-500 dark:text-slate-400'>
                                {taken}
                              </td>
                              <td className='px-4 py-4 whitespace-nowrap text-center text-sm text-slate-500 dark:text-slate-400'>
                                {missed}
                              </td>
                              <td className='px-4 py-4 whitespace-nowrap text-center text-sm text-slate-500 dark:text-slate-400'>
                                {upcoming}
                              </td>
                              <td className='px-4 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400'>
                                {formatLastTaken(lastTakenAt)}
                              </td>
                              <td
                                className={`px-4 py-4 whitespace-nowrap text-right text-sm font-bold ${adherenceColor}`}
                              >
                                {adherence}%
                              </td>
                            </tr>
                          );
                        }
                      )}
                    </tbody>
                  </table>
                </div>
              </section>
            </>
          ) : (
            <div className='text-center py-10'>
              <BarChartIcon 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'>
                Not enough data to display stats.
              </p>
              <p className='text-sm text-slate-400 dark:text-slate-500'>
                Statistics will appear here once you start tracking your 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 StatsModal;
