
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ResourceType, User } from '../types';
import { useResources, useCreateResource } from '../hooks/useBusiness';
import { useAppointments } from '../hooks/useAppointments';
import ResourceCalendar from '../components/ResourceCalendar';
import Portal from '../components/Portal';
import {
  Plus,
  MoreHorizontal,
  User as UserIcon,
  Home,
  Wrench,
  Eye,
  Calendar
} from 'lucide-react';

const ResourceIcon: React.FC<{ type: ResourceType }> = ({ type }) => {
  switch (type) {
    case 'STAFF':
      return <UserIcon size={16} className="text-blue-500" />;
    case 'ROOM':
      return <Home size={16} className="text-green-500" />;
    case 'EQUIPMENT':
      return <Wrench size={16} className="text-purple-500" />;
    default:
      return null;
  }
};

interface ResourcesProps {
  onMasquerade: (user: User) => void;
  effectiveUser: User;
}

const Resources: React.FC<ResourcesProps> = ({ onMasquerade, effectiveUser }) => {
  const { t } = useTranslation();
  // All hooks must be called at the top, before any conditional returns
  const { data: resources = [], isLoading, error } = useResources();
  const [isAddModalOpen, setIsAddModalOpen] = React.useState(false);
  const [newResourceType, setNewResourceType] = React.useState<ResourceType>('STAFF');
  const [newResourceName, setNewResourceName] = React.useState('');
  const [selectedResource, setSelectedResource] = React.useState<{ id: string; name: string } | null>(null);
  const createResourceMutation = useCreateResource();

  // Fetch ALL appointments (not filtered by date) to count per resource
  // We filter client-side for future appointments
  const { data: allAppointments = [] } = useAppointments();

  // Count future appointments per resource
  const appointmentCountByResource = useMemo(() => {
    const counts: Record<string, number> = {};
    const now = new Date();
    allAppointments.forEach(apt => {
      // Only count future appointments that have a resource assigned
      if (apt.resourceId && new Date(apt.startTime) >= now) {
        counts[apt.resourceId] = (counts[apt.resourceId] || 0) + 1;
      }
    });
    return counts;
  }, [allAppointments]);

  const handleAddResource = (e: React.FormEvent) => {
    e.preventDefault();

    createResourceMutation.mutate({
      name: newResourceName,
      type: newResourceType
    }, {
      onSuccess: () => {
        setIsAddModalOpen(false);
        setNewResourceName('');
        setNewResourceType('STAFF');
      }
    });
  };

  if (isLoading) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-800 dark:text-red-300">{t('resources.errorLoading')}: {(error as Error).message}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-8 max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('resources.title')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('resources.description')}</p>
        </div>
        <button
          onClick={() => setIsAddModalOpen(true)}
          className="flex items-center justify-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors shadow-sm font-medium"
        >
          <Plus size={18} />
          {t('resources.addResource')}
        </button>
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden transition-colors duration-200">
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left">
            <thead className="text-xs text-gray-500 dark:text-gray-400 uppercase bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
              <tr>
                <th className="px-6 py-4 font-medium">{t('resources.resourceName')}</th>
                <th className="px-6 py-4 font-medium">{t('resources.type')}</th>
                <th className="px-6 py-4 font-medium">{t('resources.upcoming')}</th>
                <th className="px-6 py-4 font-medium">{t('scheduler.status')}</th>
                <th className="px-6 py-4 font-medium text-right">{t('common.actions')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              {resources.map((resource: any) => {
                return (
                  <tr key={resource.id} className="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors group">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg bg-gray-100 dark:bg-gray-700 flex items-center justify-center overflow-hidden border border-gray-200 dark:border-gray-600">
                          <ResourceIcon type={resource.type} />
                        </div>
                        <div>
                          <div className="font-medium text-gray-900 dark:text-white">{resource.name}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize ${resource.type === 'STAFF' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
                        resource.type === 'ROOM' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
                          'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300'
                        }`}>
                        {resource.type.toLowerCase()}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-1.5 text-gray-600 dark:text-gray-300">
                        <Calendar size={14} className="text-brand-500" />
                        <span className="font-medium">{appointmentCountByResource[String(resource.id)] || 0}</span>
                        <span className="text-xs text-gray-400">{t('resources.appointments')}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                        {t('resources.active')}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => setSelectedResource({ id: resource.id, name: resource.name })}
                          className="text-brand-600 hover:text-brand-500 dark:text-brand-400 dark:hover:text-brand-300 font-medium text-xs inline-flex items-center gap-1 px-3 py-1 border border-brand-200 dark:border-brand-800 rounded-lg hover:bg-brand-50 dark:hover:bg-brand-900/30 transition-colors"
                          title={`${t('resources.viewCalendar')} - ${resource.name}`}
                        >
                          <Eye size={14} /> {t('resources.viewCalendar')}
                        </button>
                        <button className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
                          <MoreHorizontal size={18} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {resources.length === 0 && (
            <div className="p-12 text-center">
              <p className="text-gray-500 dark:text-gray-400">{t('resources.noResourcesFound')}</p>
            </div>
          )}
        </div>
      </div>

      {/* Add Resource Modal */}
      {isAddModalOpen && (
        <Portal>
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">{t('resources.addNewResource')}</h3>
                <button onClick={() => setIsAddModalOpen(false)} className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300">
                  <span className="sr-only">{t('common.close')}</span>
                  <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            <form onSubmit={handleAddResource} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('resources.resourceType')}</label>
                <select
                  value={newResourceType}
                  onChange={(e) => setNewResourceType(e.target.value as ResourceType)}
                  className="w-full rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-brand-500 focus:border-brand-500"
                >
                  <option value="STAFF">{t('resources.staffMember')}</option>
                  <option value="ROOM">{t('resources.room')}</option>
                  <option value="EQUIPMENT">{t('resources.equipment')}</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t('resources.resourceName')}</label>
                <input
                  type="text"
                  value={newResourceName}
                  onChange={(e) => setNewResourceName(e.target.value)}
                  className="w-full rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-brand-500 focus:border-brand-500"
                  placeholder={newResourceType === 'STAFF' ? 'e.g. Sarah (Stylist)' : newResourceType === 'ROOM' ? 'e.g. Massage Room 1' : 'e.g. Laser Machine'}
                  required
                />
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  {t('resources.resourceNote')}
                </p>
              </div>

              <div className="flex justify-end gap-3 mt-6">
                <button
                  type="button"
                  onClick={() => setIsAddModalOpen(false)}
                  className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600"
                >
                  {t('common.cancel')}
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700"
                >
                  {t('resources.createResource')}
                </button>
              </div>
              </form>
            </div>
          </div>
        </Portal>
      )}

      {/* Resource Calendar Modal */}
      {selectedResource && (
        <ResourceCalendar
          resourceId={selectedResource.id}
          resourceName={selectedResource.name}
          onClose={() => setSelectedResource(null)}
        />
      )}
    </div>
  );
};

export default Resources;