import React, { useState, useEffect, useRef } from 'react';
import { User, UserSettings } from '../../types';
import { CameraIcon, TrashIcon, UserIcon } from '../icons/Icons';

interface AccountModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: User;
  settings: UserSettings;
  onUpdateUser: (user: User) => Promise<void>;
  onUpdateSettings: (settings: UserSettings) => Promise<void>;
  onDeleteAllData: () => Promise<void>;
}

const AccountModal: React.FC<AccountModalProps> = ({
  isOpen,
  onClose,
  user,
  settings,
  onUpdateUser,
  onUpdateSettings,
  onDeleteAllData,
}) => {
  const [username, setUsername] = useState(user.username);
  const [successMessage, setSuccessMessage] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const modalRef = useRef<HTMLDivElement>(null);
  const closeButtonRef = useRef<HTMLButtonElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

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

  const handleUsernameSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (username.trim() && username !== user.username) {
      setIsSaving(true);
      try {
        await onUpdateUser({ ...user, username: username.trim() });
        setSuccessMessage('Username updated successfully!');
        setTimeout(() => setSuccessMessage(''), 3000);
      } catch {
        alert('Failed to update username.');
      } finally {
        setIsSaving(false);
      }
    }
  };

  const handleToggleNotifications = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    onUpdateSettings({ ...settings, notificationsEnabled: e.target.checked });
  };

  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = async () => {
        setIsSaving(true);
        try {
          await onUpdateUser({ ...user, avatar: reader.result as string });
        } finally {
          setIsSaving(false);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleRemoveAvatar = async () => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { avatar, ...userWithoutAvatar } = user;
    setIsSaving(true);
    try {
      await onUpdateUser(userWithoutAvatar);
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await onDeleteAllData();
    } catch {
      alert('Failed to delete data.');
    } finally {
      setIsDeleting(false);
    }
  };

  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='account-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='account-title'
            className='text-xl font-semibold text-slate-800 dark:text-slate-100'
          >
            Account Settings
          </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 space-y-6 max-h-[60vh] overflow-y-auto'>
          <section>
            <h4 className='text-lg font-medium text-slate-700 dark:text-slate-200 mb-3'>
              Profile
            </h4>
            <div className='flex items-center space-x-4'>
              <div className='relative'>
                {user.avatar ? (
                  <img
                    src={user.avatar}
                    alt='User avatar'
                    className='w-20 h-20 rounded-full object-cover'
                  />
                ) : (
                  <span className='w-20 h-20 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center'>
                    <UserIcon className='w-10 h-10 text-slate-500' />
                  </span>
                )}
                <button
                  onClick={() => fileInputRef.current?.click()}
                  className='absolute bottom-0 right-0 bg-white dark:bg-slate-600 rounded-full p-1.5 shadow-md border border-slate-200 dark:border-slate-500 hover:bg-slate-100 dark:hover:bg-slate-500'
                  aria-label='Change profile picture'
                >
                  <CameraIcon className='w-4 h-4 text-slate-700 dark:text-slate-200' />
                </button>
                <input
                  type='file'
                  ref={fileInputRef}
                  onChange={handleAvatarChange}
                  accept='image/*'
                  className='hidden'
                />
              </div>
              <div className='flex flex-col'>
                <button
                  onClick={() => fileInputRef.current?.click()}
                  className='px-3 py-1.5 text-sm font-medium text-slate-700 bg-white border border-slate-300 rounded-md shadow-sm hover:bg-slate-50 dark:bg-slate-700 dark:text-slate-200 dark:border-slate-600 dark:hover:bg-slate-600'
                >
                  Change Picture
                </button>
                {user.avatar && (
                  <button
                    onClick={handleRemoveAvatar}
                    className='mt-2 flex items-center text-sm text-red-600 dark:text-red-500 hover:underline'
                  >
                    <TrashIcon className='w-3 h-3 mr-1' /> Remove
                  </button>
                )}
              </div>
            </div>
            <form onSubmit={handleUsernameSubmit} className='space-y-3 mt-4'>
              <div>
                <label
                  htmlFor='username'
                  className='block text-sm font-medium text-slate-600 dark:text-slate-300'
                >
                  Username
                </label>
                <div className='mt-1 flex rounded-md shadow-sm'>
                  <input
                    type='text'
                    id='username'
                    value={username}
                    onChange={e => setUsername(e.target.value)}
                    className='flex-1 block w-full min-w-0 rounded-none rounded-l-md px-3 py-2 border border-slate-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-white dark:bg-slate-700 dark:border-slate-600 dark:placeholder-slate-400 dark:text-white'
                  />
                  <button
                    type='submit'
                    className='inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-r-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 dark:focus:ring-offset-slate-800'
                    disabled={
                      username === user.username || !username.trim() || isSaving
                    }
                  >
                    {isSaving ? 'Saving...' : 'Save'}
                  </button>
                </div>
                {successMessage && (
                  <p className='text-sm text-green-600 dark:text-green-500 mt-2'>
                    {successMessage}
                  </p>
                )}
              </div>
            </form>
          </section>

          <section>
            <h4 className='text-lg font-medium text-slate-700 dark:text-slate-200 mb-3'>
              Preferences
            </h4>
            <div className='flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg'>
              <span className='font-medium text-slate-800 dark:text-slate-100'>
                Enable Notifications
              </span>
              <label
                htmlFor='notifications-toggle'
                className='relative inline-flex items-center cursor-pointer'
              >
                <input
                  type='checkbox'
                  id='notifications-toggle'
                  className='sr-only peer'
                  checked={settings.notificationsEnabled}
                  onChange={handleToggleNotifications}
                />
                <div className="w-11 h-6 bg-slate-200 dark:bg-slate-600 rounded-full peer peer-focus:ring-4 peer-focus:ring-indigo-300 dark:peer-focus:ring-indigo-800 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-slate-600 peer-checked:bg-indigo-600"></div>
              </label>
            </div>
          </section>

          <section>
            <h4 className='text-lg font-medium text-red-600 dark:text-red-500 mb-3'>
              Danger Zone
            </h4>
            <div className='p-4 border border-red-300 dark:border-red-500/50 rounded-lg'>
              <div className='flex items-center justify-between'>
                <div>
                  <p className='font-semibold text-slate-800 dark:text-slate-100'>
                    Delete All Data
                  </p>
                  <p className='text-sm text-slate-500 dark:text-slate-400'>
                    Permanently delete all your medications and history.
                  </p>
                </div>
                <button
                  onClick={handleDelete}
                  disabled={isDeleting}
                  className='px-4 py-2 text-sm font-medium text-white bg-red-600 border border-transparent rounded-md shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 dark:focus:ring-offset-slate-800 disabled:opacity-50 disabled:cursor-not-allowed flex items-center'
                >
                  {isDeleting && <Spinner />}
                  {isDeleting ? 'Deleting...' : 'Delete Data'}
                </button>
              </div>
            </div>
          </section>
        </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>
  );
};

const Spinner = () => (
  <svg
    className='animate-spin -ml-1 mr-3 h-5 w-5 text-white'
    xmlns='http://www.w3.org/2000/svg'
    fill='none'
    viewBox='0 0 24 24'
  >
    <circle
      className='opacity-25'
      cx='12'
      cy='12'
      r='10'
      stroke='currentColor'
      strokeWidth='4'
    ></circle>
    <path
      className='opacity-75'
      fill='currentColor'
      d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
    ></path>
  </svg>
);

export default AccountModal;
