'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import {
  profileSectionsService,
  profileFieldsService,
  agentTypesService,
  ProfileSection,
  ProfileField,
  AgentType,
  CreateFieldDto,
  UpdateFieldDto,
  FieldType,
  FieldOption,
  RangeConfig,
  FieldValidation,
  FieldUiConfig,
  FIELD_TYPES,
  getErrorMessage,
} from '@/services';

type FieldModalType = 'create' | 'edit' | 'delete' | null;
type AssignModalType = 'assign' | 'editAssignment' | null;

const REQUIRES_OPTIONS: FieldType[] = ['SELECT', 'RADIO', 'MULTI_SELECT', 'CHECKBOX_GROUP'];

export default function SectionDetailPage() {
  const router = useRouter();
  const params = useParams();
  const sectionId = params.id as string;

  const [section, setSection] = useState<ProfileSection | null>(null);
  const [fields, setFields] = useState<ProfileField[]>([]);
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');

  // Field Modal state
  const [fieldModalType, setFieldModalType] = useState<FieldModalType>(null);
  const [selectedField, setSelectedField] = useState<ProfileField | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [modalError, setModalError] = useState('');

  // Assign Modal state
  const [assignModalType, setAssignModalType] = useState<AssignModalType>(null);

  // Field Form state
  const [fieldForm, setFieldForm] = useState<CreateFieldDto>({
    sectionId: '',
    name: '',
    fieldType: 'TEXT',
    description: '',
    placeholder: '',
    defaultValue: '',
    sortOrder: 0,
    isActive: true,
    isRequired: false,
    isSearchableOnly: false,
    options: [],
    rangeConfig: undefined,
    validation: undefined,
    uiConfig: undefined,
  });

  const [editSlug, setEditSlug] = useState('');

  // Options editor state
  const [optionInput, setOptionInput] = useState({ value: '', label: '' });

  // Assignment form state
  const [assignForm, setAssignForm] = useState({
    agentTypeId: '',
    sortOrder: 0,
    isRequired: false,
  });

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    setError('');
    try {
      const [sectionData, fieldsData, agentTypesData] = await Promise.all([
        profileSectionsService.getById(sectionId),
        profileFieldsService.getAll(sectionId, true),
        agentTypesService.getAll(true),
      ]);
      setSection(sectionData);
      setFields(fieldsData);
      setAgentTypes(agentTypesData);
    } catch (err) {
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
      if (errorMessage.includes('Unauthorized')) {
        router.push('/login');
      }
    } finally {
      setIsLoading(false);
    }
  }, [sectionId, router]);

  useEffect(() => {
    if (sectionId) {
      fetchData();
    }
  }, [sectionId, fetchData]);

  // Field Modal handlers
  const openCreateFieldModal = () => {
    setFieldForm({
      sectionId,
      name: '',
      fieldType: 'TEXT',
      description: '',
      placeholder: '',
      defaultValue: '',
      sortOrder: fields.length,
      isActive: true,
      isRequired: false,
      isSearchableOnly: false,
      options: [],
      rangeConfig: undefined,
      validation: undefined,
      uiConfig: undefined,
    });
    setOptionInput({ value: '', label: '' });
    setModalError('');
    setFieldModalType('create');
  };

  const openEditFieldModal = (field: ProfileField) => {
    setSelectedField(field);
    setEditSlug(field.slug);
    setFieldForm({
      sectionId,
      name: field.name,
      fieldType: field.fieldType,
      description: field.description || '',
      placeholder: field.placeholder || '',
      defaultValue: field.defaultValue || '',
      sortOrder: field.sortOrder,
      isActive: field.isActive,
      isRequired: field.isRequired,
      isSearchableOnly: field.isSearchableOnly,
      options: field.options || [],
      rangeConfig: field.rangeConfig || undefined,
      validation: field.validation || undefined,
      uiConfig: field.uiConfig || undefined,
    });
    setOptionInput({ value: '', label: '' });
    setModalError('');
    setFieldModalType('edit');
  };

  const openDeleteFieldModal = (field: ProfileField) => {
    setSelectedField(field);
    setModalError('');
    setFieldModalType('delete');
  };

  const closeFieldModal = () => {
    setFieldModalType(null);
    setSelectedField(null);
    setModalError('');
  };

  const handleCreateField = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setModalError('');
    try {
      await profileFieldsService.create(fieldForm);
      closeFieldModal();
      fetchData();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleUpdateField = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedField) return;
    setIsSubmitting(true);
    setModalError('');
    try {
      const { sectionId: _, ...updateData } = fieldForm;
      const updatePayload: UpdateFieldDto = { ...updateData };
      if (editSlug && editSlug !== selectedField.slug) {
        updatePayload.slug = editSlug;
      }
      await profileFieldsService.update(selectedField.id, updatePayload);
      closeFieldModal();
      fetchData();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDeleteField = async () => {
    if (!selectedField) return;
    setIsSubmitting(true);
    setModalError('');
    try {
      await profileFieldsService.delete(selectedField.id);
      closeFieldModal();
      fetchData();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  // Options management
  const addOption = () => {
    if (!optionInput.value.trim() || !optionInput.label.trim()) return;
    setFieldForm({
      ...fieldForm,
      options: [...(fieldForm.options || []), { ...optionInput }],
    });
    setOptionInput({ value: '', label: '' });
  };

  const removeOption = (index: number) => {
    setFieldForm({
      ...fieldForm,
      options: (fieldForm.options || []).filter((_, i) => i !== index),
    });
  };

  // Validation management
  const updateValidation = (key: keyof FieldValidation, value: number | string) => {
    const current = fieldForm.validation || {};
    const parsed = typeof value === 'string' && value === '' ? undefined : typeof value === 'string' ? (isNaN(Number(value)) ? value : Number(value)) : value;
    const updated = { ...current, [key]: parsed };
    // Remove undefined keys
    Object.keys(updated).forEach((k) => {
      if (updated[k as keyof FieldValidation] === undefined || updated[k as keyof FieldValidation] === '') {
        delete updated[k as keyof FieldValidation];
      }
    });
    setFieldForm({ ...fieldForm, validation: Object.keys(updated).length > 0 ? updated : undefined });
  };

  // UI Config management
  const updateUiConfig = (key: keyof FieldUiConfig, value: number | string | boolean) => {
    const current = fieldForm.uiConfig || {};
    const updated = { ...current, [key]: value };
    if (value === '' || value === undefined) {
      delete updated[key as keyof FieldUiConfig];
    }
    setFieldForm({ ...fieldForm, uiConfig: Object.keys(updated).length > 0 ? updated : undefined });
  };

  // Range config management
  const updateRangeConfig = (key: keyof RangeConfig, value: number | string) => {
    setFieldForm({
      ...fieldForm,
      rangeConfig: {
        min: fieldForm.rangeConfig?.min || 0,
        max: fieldForm.rangeConfig?.max || 100,
        step: fieldForm.rangeConfig?.step,
        unit: fieldForm.rangeConfig?.unit,
        [key]: typeof value === 'string' ? value : Number(value),
      },
    });
  };

  // Toggle field status
  const toggleFieldStatus = async (field: ProfileField) => {
    try {
      await profileFieldsService.update(field.id, { isActive: !field.isActive });
      fetchData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
  };

  // Assignment handlers
  const openAssignModal = () => {
    setAssignForm({
      agentTypeId: '',
      sortOrder: 0,
      isRequired: false,
    });
    setModalError('');
    setAssignModalType('assign');
  };

  const closeAssignModal = () => {
    setAssignModalType(null);
    setModalError('');
  };

  const openEditAssignmentModal = (ats: { agentTypeId: string; sortOrder: number; isRequired: boolean }) => {
    setAssignForm({
      agentTypeId: ats.agentTypeId,
      sortOrder: ats.sortOrder,
      isRequired: ats.isRequired,
    });
    setModalError('');
    setAssignModalType('editAssignment');
  };

  const handleUpdateAssignment = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setModalError('');
    try {
      await profileSectionsService.updateAssignment(sectionId, assignForm.agentTypeId, {
        sortOrder: assignForm.sortOrder,
        isRequired: assignForm.isRequired,
      });
      closeAssignModal();
      fetchData();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleAssign = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setModalError('');
    try {
      await profileSectionsService.assignToAgentType(sectionId, assignForm);
      closeAssignModal();
      fetchData();
    } catch (err) {
      setModalError(getErrorMessage(err));
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRemoveAssignment = async (agentTypeId: string) => {
    if (!confirm('Remove this section from the agent type?')) return;
    try {
      await profileSectionsService.removeFromAgentType(sectionId, agentTypeId);
      fetchData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
  };

  const handleToggleGlobal = async (newIsGlobal: boolean) => {
    try {
      await profileSectionsService.update(sectionId, { isGlobal: newIsGlobal });
      fetchData();
    } catch (err) {
      setError(getErrorMessage(err));
    }
  };

  const getFieldTypeLabel = (type: FieldType) => {
    const found = FIELD_TYPES.find((ft) => ft.value === type);
    return found?.label || type;
  };

  if (isLoading) {
    return (
      <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>
    );
  }

  if (!section) {
    return (
      <div className="text-center py-12">
        <p className="text-[#666666] font-serif">Section not found</p>
        <Link href="/dashboard/profile-sections" className="mt-4 text-[#f5a623] hover:underline">
          Back to sections
        </Link>
      </div>
    );
  }

  // Get assigned agent types
  const assignedAgentTypeIds = section.agentTypeSections?.map((ats) => ats.agentTypeId) || [];
  const availableAgentTypes = agentTypes.filter((at) => !assignedAgentTypeIds.includes(at.id));

  return (
    <div>
      {/* Breadcrumb */}
      <div className="mb-4">
        <Link href="/dashboard/profile-sections" className="text-[#f5a623] hover:underline text-sm">
          &larr; Back to Profile Sections
        </Link>
      </div>

      {/* Page Header */}
      <div className="mb-6 flex justify-between items-start">
        <div>
          <div className="flex items-center">
            {section.icon && <span className="text-2xl mr-2">{section.icon}</span>}
            <h1 className="text-2xl font-bold text-[#00293d] font-fractul">{section.name}</h1>
            {section.isSystem && (
              <span className="ml-3 px-2 py-1 text-xs font-semibold rounded-full bg-amber-100 text-amber-800">
                System
              </span>
            )}
            {section.isGlobal && (
              <span className="ml-3 px-2 py-1 text-xs font-semibold rounded-full bg-[#fff7ed] text-[#f5a623]">
                Global
              </span>
            )}
          </div>
          <p className="text-[#666666] font-serif mt-1">{section.description || 'No description'}</p>
        </div>
        <div className="flex space-x-3">
          <button
            onClick={fetchData}
            className="px-4 py-2 border border-[#e5e7eb] hover:bg-[#f5f9f8] text-[#00293d] text-sm font-medium rounded-lg transition-colors"
          >
            Refresh
          </button>
        </div>
      </div>

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

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Fields Section */}
        <div className="lg:col-span-2">
          <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]">
            <div className="px-6 py-4 border-b border-[#e5e7eb] flex justify-between items-center">
              <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Fields ({fields.length})</h2>
              <button
                onClick={openCreateFieldModal}
                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 Field
              </button>
            </div>

            <div className="divide-y divide-[#e5e7eb]">
              {fields.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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                  </svg>
                  <p className="mt-2 text-[#666666] font-serif">No fields defined yet</p>
                  <button
                    onClick={openCreateFieldModal}
                    className="mt-4 px-4 py-2 bg-[#f5a623] hover:bg-[#e09620] text-white text-sm font-medium rounded-lg transition-colors"
                  >
                    Add First Field
                  </button>
                </div>
              ) : (
                fields.map((field, index) => (
                  <div key={field.id} className="px-6 py-4 hover:bg-[#f5f9f8]">
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="flex items-center flex-wrap gap-2">
                          <span className="text-[#9ca3af] mr-1 text-sm">#{index + 1}</span>
                          <span className="font-medium text-[#00293d]">{field.name}</span>
                          {field.isRequired && (
                            <span className="text-red-500 text-xs">*required</span>
                          )}
                          {field.isSearchableOnly && (
                            <span className="px-2 py-0.5 text-xs font-medium rounded-full bg-amber-100 text-amber-800">
                              Search Only
                            </span>
                          )}
                        </div>
                        <div className="mt-1 flex items-center space-x-3 text-sm">
                          <span className="px-2 py-0.5 bg-[#e8f0ee] text-[#666666] rounded">
                            {getFieldTypeLabel(field.fieldType)}
                          </span>
                          <span className="text-[#9ca3af]">{field.slug}</span>
                          {field.placeholder && (
                            <span className="text-[#9ca3af] truncate max-w-xs">
                              placeholder: {field.placeholder}
                            </span>
                          )}
                        </div>
                        {field.options && field.options.length > 0 && (
                          <div className="mt-2 flex flex-wrap gap-1">
                            {(field.options as FieldOption[]).slice(0, 5).map((opt, i) => (
                              <span key={i} className="px-2 py-0.5 bg-[#e8f0ee] text-[#5ba4a4] text-xs rounded">
                                {opt.label}
                              </span>
                            ))}
                            {field.options.length > 5 && (
                              <span className="px-2 py-0.5 bg-[#e8f0ee] text-[#666666] text-xs rounded">
                                +{field.options.length - 5} more
                              </span>
                            )}
                          </div>
                        )}
                      </div>
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={() => toggleFieldStatus(field)}
                          className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            field.isActive
                              ? 'bg-green-100 text-green-800'
                              : 'bg-gray-100 text-gray-800'
                          }`}
                        >
                          {field.isActive ? 'Active' : 'Inactive'}
                        </button>
                        <button
                          onClick={() => openEditFieldModal(field)}
                          className="p-1 text-[#9ca3af] hover:text-[#f5a623]"
                        >
                          <svg className="w-5 h-5" 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>
                        </button>
                        <button
                          onClick={() => openDeleteFieldModal(field)}
                          className="p-1 text-[#9ca3af] hover:text-red-600"
                        >
                          <svg className="w-5 h-5" 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>
                        </button>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Agent Type Assignments */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]">
            <div className="px-6 py-4 border-b border-[#e5e7eb] flex justify-between items-center">
              <h2 className="text-lg font-semibold text-[#00293d] font-fractul">Agent Types</h2>
              {availableAgentTypes.length > 0 && (
                <button
                  onClick={openAssignModal}
                  className="px-3 py-1.5 bg-[#f5a623] hover:bg-[#e09620] text-white text-sm font-medium rounded-lg transition-colors"
                >
                  Assign
                </button>
              )}
            </div>
            <div className="p-6">
              {/* Global toggle */}
              <div className="flex items-center justify-between p-3 bg-[#f5f9f8] rounded-xl mb-4">
                <div>
                  <p className="font-medium text-[#00293d]">Available to all agent types</p>
                  <p className="text-xs text-[#666666]">
                    {section.isGlobal
                      ? 'This section appears for all agent types by default'
                      : 'Only assigned agent types will see this section'}
                  </p>
                </div>
                <button
                  onClick={() => handleToggleGlobal(!section.isGlobal)}
                  className={`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${
                    section.isGlobal ? 'bg-[#5ba4a4]' : 'bg-[#e8f0ee]'
                  }`}
                  role="switch"
                  aria-checked={section.isGlobal}
                >
                  <span
                    className={`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${
                      section.isGlobal ? 'translate-x-5' : 'translate-x-0'
                    }`}
                  />
                </button>
              </div>

              {/* Specific agent type assignments */}
              {section.agentTypeSections && section.agentTypeSections.length > 0 ? (
                <div className="space-y-3">
                  <p className="text-xs text-[#666666] font-medium uppercase tracking-wide mb-2">
                    Specific Assignments
                  </p>
                  {section.agentTypeSections.map((ats) => {
                    const agentType = agentTypes.find((at) => at.id === ats.agentTypeId);
                    return (
                      <div
                        key={ats.id}
                        className="flex items-center justify-between p-3 bg-[#f5f9f8] rounded-xl"
                      >
                        <div>
                          <p className="font-medium text-[#00293d]">{agentType?.name || 'Unknown'}</p>
                          <p className="text-xs text-[#666666]">
                            {ats.isRequired ? 'Required' : 'Optional'} &bull; Order: {ats.sortOrder}
                          </p>
                        </div>
                        <div className="flex items-center space-x-1">
                          <button
                            onClick={() => openEditAssignmentModal(ats)}
                            className="p-1 text-[#9ca3af] hover:text-[#f5a623]"
                            title="Edit assignment"
                          >
                            <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>
                          </button>
                          <button
                            onClick={() => handleRemoveAssignment(ats.agentTypeId)}
                            className="p-1 text-[#9ca3af] hover:text-red-600"
                            title="Remove assignment"
                          >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="text-center py-4">
                  <p className="text-[#666666] text-sm font-serif">
                    {section.isGlobal
                      ? 'No specific agent type configurations yet'
                      : 'Not assigned to any agent type'}
                  </p>
                  {availableAgentTypes.length > 0 && (
                    <button
                      onClick={openAssignModal}
                      className="mt-3 text-[#f5a623] hover:underline text-sm"
                    >
                      {section.isGlobal ? 'Add specific configuration' : 'Assign to agent type'}
                    </button>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Field Create/Edit Modal */}
      {(fieldModalType === 'create' || fieldModalType === 'edit') && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50 overflow-y-auto">
          <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]-xl max-w-2xl w-full mx-4 my-8">
            <div className="px-6 py-4 border-b border-[#e5e7eb]">
              <h3 className="text-lg font-semibold text-[#00293d] font-fractul">
                {fieldModalType === 'create' ? 'Create Field' : 'Edit Field'}
              </h3>
            </div>
            <form onSubmit={fieldModalType === 'create' ? handleCreateField : handleUpdateField}>
              <div className="px-6 py-4 space-y-4 max-h-[60vh] overflow-y-auto">
                {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 className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={fieldForm.name}
                      onChange={(e) => setFieldForm({ ...fieldForm, 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>
                  {fieldModalType === 'edit' && (
                    <div>
                      <label className="block text-sm font-medium text-[#00293d] mb-1">
                        Slug
                      </label>
                      <input
                        type="text"
                        value={editSlug}
                        onChange={(e) => setEditSlug(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'))}
                        className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white font-mono text-sm"
                      />
                    </div>
                  )}
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Field Type <span className="text-red-500">*</span>
                    </label>
                    <select
                      value={fieldForm.fieldType}
                      onChange={(e) => setFieldForm({ ...fieldForm, fieldType: e.target.value as FieldType })}
                      className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-[#00293d] bg-white"
                    >
                      {FIELD_TYPES.map((ft) => (
                        <option key={ft.value} value={ft.value}>
                          {ft.label} - {ft.description}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    Description
                  </label>
                  <input
                    type="text"
                    value={fieldForm.description}
                    onChange={(e) => setFieldForm({ ...fieldForm, description: 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="Help text for this field"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Placeholder
                    </label>
                    <input
                      type="text"
                      value={fieldForm.placeholder}
                      onChange={(e) => setFieldForm({ ...fieldForm, placeholder: 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"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Default Value
                    </label>
                    <input
                      type="text"
                      value={fieldForm.defaultValue}
                      onChange={(e) => setFieldForm({ ...fieldForm, defaultValue: 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"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Sort Order
                    </label>
                    <input
                      type="number"
                      value={fieldForm.sortOrder === 0 ? '' : fieldForm.sortOrder}
                      onChange={(e) => setFieldForm({ ...fieldForm, 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 space-x-6 pt-6">
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="fieldIsActive"
                        checked={fieldForm.isActive}
                        onChange={(e) => setFieldForm({ ...fieldForm, isActive: e.target.checked })}
                        className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                      />
                      <label htmlFor="fieldIsActive" className="ml-2 text-sm text-[#00293d] font-serif">
                        Active
                      </label>
                    </div>
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="fieldIsRequired"
                        checked={fieldForm.isRequired}
                        onChange={(e) => setFieldForm({ ...fieldForm, isRequired: e.target.checked })}
                        className="rounded border-[#e5e7eb] text-red-600 focus:ring-0"
                      />
                      <label htmlFor="fieldIsRequired" className="ml-2 text-sm text-[#00293d] font-serif">
                        Required
                      </label>
                    </div>
                  </div>
                </div>

                {/* Search Only Toggle */}
                <div className="border border-amber-200 rounded-lg p-4 bg-amber-50">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <label htmlFor="fieldIsSearchableOnly" className="text-sm font-medium text-[#00293d]">
                        Search Only (Hidden from Public Profile)
                      </label>
                      <p className="text-xs text-[#666666] font-serif mt-1">
                        This field will be shown in the agent edit form and used for search filtering,
                        but will NOT be visible on the public agent profile page.
                      </p>
                    </div>
                    <input
                      type="checkbox"
                      id="fieldIsSearchableOnly"
                      checked={fieldForm.isSearchableOnly}
                      onChange={(e) => setFieldForm({ ...fieldForm, isSearchableOnly: e.target.checked })}
                      className="mt-1 rounded border-[#e5e7eb] text-amber-600 focus:ring-0"
                    />
                  </div>
                </div>

                {/* Options Editor for SELECT, RADIO, MULTI_SELECT, CHECKBOX_GROUP */}
                {REQUIRES_OPTIONS.includes(fieldForm.fieldType) && (
                  <div className="border border-[#e5e7eb] rounded-xl p-4">
                    <label className="block text-sm font-medium text-[#00293d] mb-3">
                      Options
                    </label>
                    <div className="flex space-x-2 mb-3">
                      <input
                        type="text"
                        value={optionInput.value}
                        onChange={(e) => setOptionInput({ ...optionInput, value: e.target.value })}
                        placeholder="Value"
                        className="flex-1 px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                      />
                      <input
                        type="text"
                        value={optionInput.label}
                        onChange={(e) => setOptionInput({ ...optionInput, label: e.target.value })}
                        placeholder="Label"
                        className="flex-1 px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                      />
                      <button
                        type="button"
                        onClick={addOption}
                        className="px-4 py-2 bg-[#e8f0ee] hover:bg-[#d5e5e1] text-[#00293d] text-sm font-medium rounded-lg transition-colors"
                      >
                        Add
                      </button>
                    </div>
                    {fieldForm.options && fieldForm.options.length > 0 && (
                      <div className="space-y-2">
                        {fieldForm.options.map((opt, index) => (
                          <div
                            key={index}
                            className="flex items-center justify-between px-3 py-2 bg-[#f5f9f8] rounded"
                          >
                            <span className="text-sm">
                              <span className="font-medium text-[#00293d]">{opt.label}</span>
                              <span className="text-xs text-[#9ca3af] ml-2">({opt.value})</span>
                            </span>
                            <button
                              type="button"
                              onClick={() => removeOption(index)}
                              className="text-red-500 hover:text-red-700"
                            >
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                              </svg>
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {/* Range Config for RANGE type */}
                {fieldForm.fieldType === 'RANGE' && (
                  <div className="border border-[#e5e7eb] rounded-xl p-4">
                    <label className="block text-sm font-medium text-[#00293d] mb-3">
                      Range Configuration
                    </label>
                    <div className="grid grid-cols-4 gap-3">
                      <div>
                        <label className="block text-xs text-[#666666] mb-1">Min</label>
                        <input
                          type="number"
                          value={fieldForm.rangeConfig?.min || 0}
                          onChange={(e) => updateRangeConfig('min', e.target.value)}
                          onFocus={(e) => e.target.select()}
                          className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white"
                        />
                      </div>
                      <div>
                        <label className="block text-xs text-[#666666] mb-1">Max</label>
                        <input
                          type="number"
                          value={fieldForm.rangeConfig?.max || 100}
                          onChange={(e) => updateRangeConfig('max', e.target.value)}
                          onFocus={(e) => e.target.select()}
                          className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white"
                        />
                      </div>
                      <div>
                        <label className="block text-xs text-[#666666] mb-1">Step</label>
                        <input
                          type="number"
                          value={fieldForm.rangeConfig?.step || 1}
                          onChange={(e) => updateRangeConfig('step', e.target.value)}
                          onFocus={(e) => e.target.select()}
                          min={1}
                          className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white"
                        />
                      </div>
                      <div>
                        <label className="block text-xs text-[#666666] mb-1">Unit</label>
                        <input
                          type="text"
                          value={fieldForm.rangeConfig?.unit || ''}
                          onChange={(e) => updateRangeConfig('unit', e.target.value)}
                          placeholder="e.g., years"
                          className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* Validation Rules */}
                <div className="border border-[#e5e7eb] rounded-xl p-4">
                  <label className="block text-sm font-medium text-[#00293d] mb-3">
                    Validation Rules
                  </label>
                  <div className="grid grid-cols-2 gap-3">
                    {['TEXT', 'TEXTAREA', 'TAG_INPUT'].includes(fieldForm.fieldType) && (
                      <>
                        <div>
                          <label className="block text-xs text-[#666666] mb-1">Min Length</label>
                          <input
                            type="number"
                            value={fieldForm.validation?.minLength ?? ''}
                            onChange={(e) => updateValidation('minLength', e.target.value)}
                            placeholder="No min"
                            min={0}
                            className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-[#666666] mb-1">Max Length</label>
                          <input
                            type="number"
                            value={fieldForm.validation?.maxLength ?? ''}
                            onChange={(e) => updateValidation('maxLength', e.target.value)}
                            placeholder="No max"
                            min={0}
                            className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                          />
                        </div>
                      </>
                    )}
                    {['NUMBER', 'RANGE'].includes(fieldForm.fieldType) && (
                      <>
                        <div>
                          <label className="block text-xs text-[#666666] mb-1">Min Value</label>
                          <input
                            type="number"
                            value={fieldForm.validation?.min ?? ''}
                            onChange={(e) => updateValidation('min', e.target.value)}
                            placeholder="No min"
                            className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-[#666666] mb-1">Max Value</label>
                          <input
                            type="number"
                            value={fieldForm.validation?.max ?? ''}
                            onChange={(e) => updateValidation('max', e.target.value)}
                            placeholder="No max"
                            className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                          />
                        </div>
                      </>
                    )}
                    <div className="col-span-2">
                      <label className="block text-xs text-[#666666] mb-1">Pattern (regex)</label>
                      <input
                        type="text"
                        value={fieldForm.validation?.pattern ?? ''}
                        onChange={(e) => updateValidation('pattern', e.target.value)}
                        placeholder="e.g., ^[a-zA-Z]+$"
                        className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                      />
                    </div>
                  </div>
                </div>

                {/* UI Configuration */}
                <div className="border border-[#e5e7eb] rounded-xl p-4">
                  <label className="block text-sm font-medium text-[#00293d] mb-3">
                    UI Configuration
                  </label>
                  <div className="space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs text-[#666666] mb-1">Columns (grid layout)</label>
                        <input
                          type="number"
                          value={fieldForm.uiConfig?.columns ?? ''}
                          onChange={(e) => updateUiConfig('columns', e.target.value ? Number(e.target.value) : '')}
                          placeholder="Auto"
                          min={1}
                          max={4}
                          className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                        />
                      </div>
                      <div className="flex items-center pt-5">
                        <input
                          type="checkbox"
                          id="showInPreview"
                          checked={fieldForm.uiConfig?.showInPreview ?? false}
                          onChange={(e) => updateUiConfig('showInPreview', e.target.checked)}
                          className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                        />
                        <label htmlFor="showInPreview" className="ml-2 text-sm text-[#00293d] font-serif">
                          Show in Preview
                        </label>
                      </div>
                    </div>
                    <div>
                      <label className="block text-xs text-[#666666] mb-1">Help Text</label>
                      <input
                        type="text"
                        value={fieldForm.uiConfig?.helpText ?? ''}
                        onChange={(e) => updateUiConfig('helpText', e.target.value)}
                        placeholder="Additional help text shown below the field"
                        className="w-full px-3 py-2 border border-[#e5e7eb] rounded-xl focus:outline-none focus:border-[#f5a623] text-sm text-[#00293d] bg-white placeholder:text-[#666666]"
                      />
                    </div>
                  </div>
                </div>
              </div>
              <div className="px-6 py-4 border-t border-[#e5e7eb] flex justify-end space-x-3">
                <button
                  type="button"
                  onClick={closeFieldModal}
                  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...' : fieldModalType === 'create' ? 'Create Field' : 'Save Changes'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Field Delete Modal */}
      {fieldModalType === 'delete' && selectedField && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]-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] font-fractul">Delete Field</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 the field <span className="font-semibold">{selectedField.name}</span>?
              </p>
            </div>
            <div className="px-6 py-4 border-t border-[#e5e7eb] flex justify-end space-x-3">
              <button
                onClick={closeFieldModal}
                className="px-4 py-2 border border-[#e5e7eb] text-[#00293d] rounded-xl hover:bg-[#f5f9f8] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteField}
                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>
      )}

      {/* Assign to Agent Type Modal */}
      {(assignModalType === 'assign' || assignModalType === 'editAssignment') && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-sm border border-[#e5e7eb]-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] font-fractul">
                {assignModalType === 'editAssignment' ? 'Edit Assignment' : 'Assign to Agent Type'}
              </h3>
            </div>
            <form onSubmit={assignModalType === 'editAssignment' ? handleUpdateAssignment : handleAssign}>
              <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>
                )}
                {assignModalType === 'assign' ? (
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">
                      Agent Type <span className="text-red-500">*</span>
                    </label>
                    <select
                      value={assignForm.agentTypeId}
                      onChange={(e) => setAssignForm({ ...assignForm, agentTypeId: 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
                    >
                      <option value="">Select agent type...</option>
                      {availableAgentTypes.map((at) => (
                        <option key={at.id} value={at.id}>
                          {at.name}
                        </option>
                      ))}
                    </select>
                  </div>
                ) : (
                  <div>
                    <label className="block text-sm font-medium text-[#00293d] mb-1">Agent Type</label>
                    <p className="px-3 py-2 bg-[#f5f9f8] rounded-xl text-[#00293d] text-sm">
                      {agentTypes.find((at) => at.id === assignForm.agentTypeId)?.name || 'Unknown'}
                    </p>
                  </div>
                )}
                <div>
                  <label className="block text-sm font-medium text-[#00293d] mb-1">
                    Sort Order
                  </label>
                  <input
                    type="number"
                    value={assignForm.sortOrder === 0 ? '' : assignForm.sortOrder}
                    onChange={(e) => setAssignForm({ ...assignForm, 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="assignIsRequired"
                    checked={assignForm.isRequired}
                    onChange={(e) => setAssignForm({ ...assignForm, isRequired: e.target.checked })}
                    className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                  />
                  <label htmlFor="assignIsRequired" className="ml-2 text-sm text-[#00293d] font-serif">
                    Required section for this agent type
                  </label>
                </div>
              </div>
              <div className="px-6 py-4 border-t border-[#e5e7eb] flex justify-end space-x-3">
                <button
                  type="button"
                  onClick={closeAssignModal}
                  className="px-4 py-2 border border-[#e5e7eb] text-[#00293d] rounded-xl hover:bg-[#f5f9f8] transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting || (assignModalType === 'assign' && !assignForm.agentTypeId)}
                  className="px-4 py-2 bg-[#f5a623] text-white rounded-xl hover:bg-[#e09620] transition-colors disabled:opacity-50"
                >
                  {isSubmitting ? 'Saving...' : assignModalType === 'editAssignment' ? 'Save Changes' : 'Assign'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
