import React, { useMemo, useEffect, useRef } from 'react';
import { Medication } from '../../types';
import { TrashIcon, EditIcon, getMedicationIcon } from '../icons/Icons';

interface ManageMedicationsModalProps {
  isOpen: boolean;
  onClose: () => void;
  medications: Medication[];
  // FIX: Changed onDelete to expect the full medication object to match the parent's handler.
  onDelete: (medication: Medication) => void;
  onEdit: (medication: Medication) => void;
}

const ManageMedicationsModal: React.FC<ManageMedicationsModalProps> = ({
  isOpen,
  onClose,
  medications,
  onDelete,
  onEdit,
}) => {
  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]);

  const sortedMedications = useMemo(
    () => [...medications].sort((a, b) => a.name.localeCompare(b.name)),
    [medications]
  );

  const handleDeleteConfirmation = (medication: Medication) => {
    if (window.confirm(`Are you sure you want to delete ${medication.name}?`)) {
      // FIX: Pass the whole medication object to the onDelete handler.
      onDelete(medication);
    }
  };

  if (!isOpen) return null;

  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='manage-med-title'
    >
      <div
        className='bg-white dark:bg-slate-800 rounded-lg shadow-xl w-full max-w-lg'
        ref={modalRef}
      >
        <div className='p-6 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center'>
          <h3
            id='manage-med-title'
            className='text-xl font-semibold text-slate-800 dark:text-slate-100'
          >
            Manage Medications
          </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'>
          {sortedMedications.length > 0 ? (
            <ul className='space-y-3'>
              {sortedMedications.map(med => {
                const MedicationIcon = getMedicationIcon(med.icon);
                return (
                  // FIX: The Medication type has `_id`, not `id`. Used for the key.
                  <li
                    key={med._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'>
                      <MedicationIcon className='w-6 h-6 text-indigo-500 dark:text-indigo-400 flex-shrink-0' />
                      <div>
                        <p className='font-semibold text-slate-800 dark:text-slate-100'>
                          {med.name}
                        </p>
                        <p className='text-sm text-slate-500 dark:text-slate-400'>
                          {med.dosage} &bull; {med.frequency}
                        </p>
                        {med.notes && (
                          <p className='text-xs text-slate-400 dark:text-slate-500 mt-1 italic'>
                            Note: "{med.notes}"
                          </p>
                        )}
                      </div>
                    </div>
                    <div className='flex items-center space-x-1'>
                      <button
                        onClick={() => onEdit(med)}
                        className='p-2 text-indigo-600 hover:bg-indigo-100 dark:text-indigo-400 dark:hover:bg-slate-700 rounded-full'
                        aria-label={`Edit ${med.name}`}
                      >
                        <EditIcon className='w-5 h-5' />
                      </button>
                      <button
                        onClick={() => handleDeleteConfirmation(med)}
                        className='p-2 text-red-500 hover:bg-red-100 dark:text-red-400 dark:hover:bg-slate-700 rounded-full'
                        aria-label={`Delete ${med.name}`}
                      >
                        <TrashIcon className='w-5 h-5' />
                      </button>
                    </div>
                  </li>
                );
              })}
            </ul>
          ) : (
            <p className='text-center text-slate-500 dark:text-slate-400 py-8'>
              No medications have been added yet.
            </p>
          )}
        </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 ManageMedicationsModal;
