/**
 * Resource Types Settings Page
 *
 * Define and manage custom resource types (e.g., Stylist, Treatment Room, Equipment).
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';
import { Layers, Plus, X, Pencil, Trash2, Users } from 'lucide-react';
import { Business, User } from '../../types';
import { useResourceTypes, useCreateResourceType, useUpdateResourceType, useDeleteResourceType } from '../../hooks/useResourceTypes';

const ResourceTypesSettings: React.FC = () => {
  const { t } = useTranslation();
  const { business, user } = useOutletContext<{
    business: Business;
    user: User;
  }>();

  const { data: resourceTypes = [], isLoading } = useResourceTypes();
  const createResourceType = useCreateResourceType();
  const updateResourceType = useUpdateResourceType();
  const deleteResourceType = useDeleteResourceType();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingType, setEditingType] = useState<any>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    category: 'OTHER' as 'STAFF' | 'OTHER',
    iconName: '',
  });

  const isOwner = user.role === 'owner';

  const openCreateModal = () => {
    setEditingType(null);
    setFormData({ name: '', description: '', category: 'OTHER', iconName: '' });
    setIsModalOpen(true);
  };

  const openEditModal = (type: any) => {
    setEditingType(type);
    setFormData({
      name: type.name,
      description: type.description || '',
      category: type.category,
      iconName: type.icon_name || type.iconName || '',
    });
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setEditingType(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingType) {
        await updateResourceType.mutateAsync({
          id: editingType.id,
          updates: formData,
        });
      } else {
        await createResourceType.mutateAsync(formData);
      }
      closeModal();
    } catch (error) {
      console.error('Failed to save resource type:', error);
    }
  };

  const handleDelete = async (id: string, name: string) => {
    if (window.confirm(`Are you sure you want to delete the "${name}" resource type?`)) {
      try {
        await deleteResourceType.mutateAsync(id);
      } catch (error: any) {
        alert(error.response?.data?.error || 'Failed to delete resource type');
      }
    }
  };

  if (!isOwner) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          Only the business owner can access these settings.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
          <Layers className="text-indigo-500" />
          {t('settings.resourceTypes.title', 'Resource Types')}
        </h2>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          Define custom types for your resources (e.g., Stylist, Treatment Room, Equipment).
        </p>
      </div>

      {/* Resource Types List */}
      <section className="bg-white dark:bg-gray-800 p-6 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              {t('settings.resourceTypes.list', 'Your Resource Types')}
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              {t('settings.resourceTypes.listDescription', 'Create categories to organize your resources.')}
            </p>
          </div>
          <button
            onClick={openCreateModal}
            className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium text-sm"
          >
            <Plus size={16} />
            {t('settings.addResourceType', 'Add Type')}
          </button>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
          </div>
        ) : resourceTypes.length === 0 ? (
          <div className="text-center py-8 text-gray-500 dark:text-gray-400">
            <Layers size={40} className="mx-auto mb-2 opacity-30" />
            <p>{t('settings.noResourceTypes', 'No custom resource types yet.')}</p>
            <p className="text-sm mt-1">{t('settings.addFirstResourceType', 'Add your first resource type to categorize your resources.')}</p>
          </div>
        ) : (
          <div className="space-y-3">
            {resourceTypes.map((type: any) => {
              const isDefault = type.is_default || type.isDefault;
              return (
                <div
                  key={type.id}
                  className="p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3">
                      <div className={`w-10 h-10 rounded-lg flex items-center justify-center shrink-0 ${
                        type.category === 'STAFF' ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400' : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
                      }`}>
                        {type.category === 'STAFF' ? <Users size={20} /> : <Layers size={20} />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                          {type.name}
                          {isDefault && (
                            <span className="px-1.5 py-0.5 text-[10px] font-medium bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                              Default
                            </span>
                          )}
                        </h4>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                          {type.category === 'STAFF' ? 'Requires staff assignment' : 'General resource'}
                        </p>
                        {type.description && (
                          <p className="text-sm text-gray-600 dark:text-gray-300 mt-1 line-clamp-2">
                            {type.description}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0 ml-2">
                      <button
                        onClick={() => openEditModal(type)}
                        className="p-2 text-gray-400 hover:text-brand-600 dark:hover:text-brand-400 transition-colors"
                        title={t('common.edit', 'Edit')}
                      >
                        <Pencil size={16} />
                      </button>
                      {!isDefault && (
                        <button
                          onClick={() => handleDelete(type.id, type.name)}
                          disabled={deleteResourceType.isPending}
                          className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400 transition-colors disabled:opacity-50"
                          title={t('common.delete', 'Delete')}
                        >
                          <Trash2 size={16} />
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </section>

      {/* Modal for Create/Edit */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between p-6 border-b border-gray-100 dark:border-gray-700 shrink-0">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                {editingType
                  ? t('settings.editResourceType', 'Edit Resource Type')
                  : t('settings.addResourceType', 'Add Resource Type')}
              </h3>
              <button
                onClick={closeModal}
                className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto">
              <div className="p-6 space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('settings.resourceTypeName', 'Name')} *
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    required
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                    placeholder={t('settings.resourceTypeNamePlaceholder', 'e.g., Stylist, Treatment Room, Camera')}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('settings.resourceTypeDescription', 'Description')}
                  </label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 resize-none"
                    placeholder={t('settings.resourceTypeDescriptionPlaceholder', 'Describe this type of resource...')}
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('settings.resourceTypeCategory', 'Category')} *
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value as 'STAFF' | 'OTHER' })}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                  >
                    <option value="STAFF">{t('settings.categoryStaff', 'Staff (requires staff assignment)')}</option>
                    <option value="OTHER">{t('settings.categoryOther', 'Other (general resource)')}</option>
                  </select>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    {formData.category === 'STAFF'
                      ? t('settings.staffCategoryHint', 'Staff resources must be assigned to a team member')
                      : t('settings.otherCategoryHint', 'General resources like rooms, equipment, or vehicles')}
                  </p>
                </div>
              </div>

              <div className="flex justify-end gap-3 p-6 border-t border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 shrink-0">
                <button
                  type="button"
                  onClick={closeModal}
                  className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                  {t('common.cancel', 'Cancel')}
                </button>
                <button
                  type="submit"
                  disabled={createResourceType.isPending || updateResourceType.isPending}
                  className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {editingType ? t('common.save', 'Save') : t('common.create', 'Create')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ResourceTypesSettings;
