'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { agentTypesService, AgentType, CreateAgentTypeDto, UpdateAgentTypeDto, getErrorMessage } from '@/services';

type ModalType = 'create' | 'edit' | 'delete' | null;

export default function AgentTypesPage() {
  const router = useRouter();
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [showInactive, setShowInactive] = useState(true);

  // Modal state
  const [modalType, setModalType] = useState<ModalType>(null);
  const [selectedType, setSelectedType] = useState<AgentType | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [modalError, setModalError] = useState('');

  // Form state
  const [formData, setFormData] = useState<CreateAgentTypeDto>({
    name: '',
    description: '',
    icon: '',
    isActive: true,
    sortOrder: 0,
  });

  useEffect(() => {
    fetchAgentTypes();
  }, [showInactive]);

  const fetchAgentTypes = async () => {
    setIsLoading(true);
    setError('');
    try {
      const data = await agentTypesService.getAll(showInactive);
      setAgentTypes(data);
    } catch (err) {
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
      if (errorMessage.includes('Unauthorized')) {
        router.push('/login');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const openCreateModal = () => {
    setFormData({
      name: '',
      description: '',
      icon: '',
      isActive: true,
      sortOrder: 0,
    });
    setModalError('');
    setModalType('create');
  };

  const openEditModal = (agentType: AgentType) => {
    setSelectedType(agentType);
    setFormData({
      name: agentType.name,
      description: agentType.description || '',
      icon: agentType.icon || '',
      isActive: agentType.isActive,
      sortOrder: agentType.sortOrder,
    });
    setModalError('');
    setModalType('edit');
  };

  const openDeleteModal = (agentType: AgentType) => {
    setSelectedType(agentType);
    setModalError('');
    setModalType('delete');
  };

  const closeModal = () => {
    setModalType(null);
    setSelectedType(null);
    setModalError('');
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setModalError('');
    try {
      await agentTypesService.create(formData);
      closeModal();
      fetchAgentTypes();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedType) return;
    setIsSubmitting(true);
    setModalError('');
    try {
      await agentTypesService.update(selectedType.id, formData as UpdateAgentTypeDto);
      closeModal();
      fetchAgentTypes();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!selectedType) return;
    setIsSubmitting(true);
    setModalError('');
    try {
      await agentTypesService.delete(selectedType.id);
      closeModal();
      fetchAgentTypes();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const toggleStatus = async (agentType: AgentType) => {
    try {
      await agentTypesService.update(agentType.id, { isActive: !agentType.isActive });
      fetchAgentTypes();
    } catch (err) {
      setError(getErrorMessage(err));
    }
  };

  return (
    <div>
      {/* Page Title */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-[#00293d] font-fractul">Agent Types</h1>
        <p className="text-[#666666] font-serif">Manage agent categories and types</p>
      </div>

      {/* Agent Types Table */}
      <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]">
        <div className="px-6 py-4 border-b border-[#e5e7eb]">
          <div className="flex justify-between items-center">
            <div className="flex items-center space-x-4">
              <label className="flex items-center space-x-2 text-sm text-[#666666] font-serif">
                <input
                  type="checkbox"
                  checked={showInactive}
                  onChange={(e) => setShowInactive(e.target.checked)}
                  className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                />
                <span>Show Inactive</span>
              </label>
            </div>
            <div className="flex space-x-3">
              <button
                onClick={fetchAgentTypes}
                className="px-4 py-2 border border-[#e5e7eb] hover:bg-[#f5f9f8] text-[#00293d] text-sm font-medium rounded-lg transition-colors flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Refresh
              </button>
              <button
                onClick={openCreateModal}
                className="px-4 py-2 bg-[#f5a623] hover:bg-[#e09620] text-white text-sm font-medium rounded-lg transition-colors flex items-center"
              >
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                Add Agent Type
              </button>
            </div>
          </div>
        </div>

        {error && (
          <div className="px-6 py-4 bg-red-50 border-b border-red-200">
            <p className="text-red-700 text-sm">{error}</p>
          </div>
        )}

        <div className="overflow-x-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#f5a623]"></div>
            </div>
          ) : agentTypes.length === 0 ? (
            <div className="text-center py-12">
              <svg className="mx-auto h-12 w-12 text-[#9ca3af]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
              <p className="mt-2 text-[#666666]">No agent types found</p>
              <button
                onClick={openCreateModal}
                className="mt-4 px-4 py-2 bg-[#f5a623] hover:bg-[#e09620] text-white text-sm font-medium rounded-lg transition-colors"
              >
                Create First Agent Type
              </button>
            </div>
          ) : (
            <table className="min-w-full divide-y divide-[#e5e7eb]">
              <thead className="bg-[#f5f9f8]">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Description
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Icon
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Sort Order
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Status
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Agents
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-[#666666] uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-[#e5e7eb]">
                {agentTypes.map((agentType) => (
                  <tr key={agentType.id} className="hover:bg-[#f5f9f8]">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-[#00293d]">{agentType.name}</div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="text-sm text-[#666666] max-w-xs truncate">
                        {agentType.description || '-'}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-[#666666]">{agentType.icon || '-'}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-[#666666]">{agentType.sortOrder}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <button
                        onClick={() => toggleStatus(agentType)}
                        className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full cursor-pointer transition-colors ${
                          agentType.isActive
                            ? 'bg-green-100 text-green-800 hover:bg-green-200'
                            : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                        }`}
                      >
                        {agentType.isActive ? 'Active' : 'Inactive'}
                      </button>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-[#666666]">{agentType._count?.agents || 0}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        onClick={() => router.push(`/dashboard/agent-types/${agentType.id}/sections`)}
                        className="text-[#5ba4a4] hover:text-[#5ba4a4]/80 mr-3 inline-flex items-center gap-1"
                        title="Sections"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                        </svg>
                        Sections
                      </button>
                      <button
                        onClick={() => openEditModal(agentType)}
                        className="text-[#f5a623] hover:text-[#e09620] mr-3 inline-flex items-center gap-1"
                        title="Edit"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                        Edit
                      </button>
                      <button
                        onClick={() => openDeleteModal(agentType)}
                        className="text-red-600 hover:text-red-900 inline-flex items-center gap-1"
                        title="Delete"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Create/Edit Modal */}
      {(modalType === 'create' || modalType === 'edit') && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
            <div className="px-6 py-4 border-b border-[#e5e7eb]">
              <h3 className="text-lg font-semibold text-[#00293d]">
                {modalType === 'create' ? 'Create Agent Type' : 'Edit Agent Type'}
              </h3>
            </div>
            <form onSubmit={modalType === 'create' ? handleCreate : handleUpdate}>
              <div className="px-6 py-4 space-y-4">
                {modalError && (
                  <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
                    <p className="text-red-700 text-sm">{modalError}</p>
                  </div>
                )}
                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white"
                    required
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    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-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    Icon (emoji or icon name)
                  </label>
                  <input
                    type="text"
                    value={formData.icon}
                    onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
                    className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white placeholder:text-[#666666]"
                    placeholder="e.g. house, building, key"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    Sort Order
                  </label>
                  <input
                    type="number"
                    value={formData.sortOrder === 0 ? '' : formData.sortOrder}
                    onChange={(e) => setFormData({ ...formData, sortOrder: parseInt(e.target.value) || 0 })}
                    onFocus={(e) => e.target.select()}
                    placeholder="0"
                    min={0}
                    className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white placeholder:text-[#666666]"
                  />
                </div>
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    id="isActive"
                    checked={formData.isActive}
                    onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
                    className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                  />
                  <label htmlFor="isActive" className="ml-2 text-sm text-[#00293d] font-serif">
                    Active
                  </label>
                </div>
              </div>
              <div className="px-6 py-4 border-t border-[#e5e7eb] flex justify-end space-x-3">
                <button
                  type="button"
                  onClick={closeModal}
                  className="px-4 py-2 border border-[#e5e7eb] text-[#00293d] rounded-xl hover:bg-[#f5f9f8] transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="px-4 py-2 bg-[#f5a623] text-white rounded-xl hover:bg-[#e09620] transition-colors disabled:opacity-50"
                >
                  {isSubmitting ? 'Saving...' : modalType === 'create' ? 'Create' : 'Save Changes'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {modalType === 'delete' && selectedType && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full mx-4">
            <div className="px-6 py-4 border-b border-[#e5e7eb]">
              <h3 className="text-lg font-semibold text-[#00293d]">Delete Agent Type</h3>
            </div>
            <div className="px-6 py-4">
              {modalError && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                  <p className="text-red-700 text-sm">{modalError}</p>
                </div>
              )}
              <p className="text-[#666666] font-serif">
                Are you sure you want to delete <span className="font-semibold">{selectedType.name}</span>?
                {selectedType._count?.agents && selectedType._count.agents > 0 && (
                  <span className="block mt-2 text-red-600 text-sm">
                    Warning: This agent type has {selectedType._count.agents} agent(s) assigned to it.
                  </span>
                )}
              </p>
            </div>
            <div className="px-6 py-4 border-t border-[#e5e7eb] flex justify-end space-x-3">
              <button
                onClick={closeModal}
                className="px-4 py-2 border border-[#e5e7eb] text-[#00293d] rounded-xl hover:bg-[#f5f9f8] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleDelete}
                disabled={isSubmitting}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
              >
                {isSubmitting ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
