'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { profileSectionsService, AgentTypeSectionsResponse, SectionOrderItem, getErrorMessage } from '@/services';

interface SectionWithOrder {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  icon: string | null;
  sortOrder: number;
  isActive: boolean;
  isGlobal: boolean;
  isSystem: boolean;
  isRequired: boolean;
  effectiveSortOrder: number;
  hasCustomOrder: boolean;
  _count?: {
    fields: number;
  };
}

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

  const [data, setData] = useState<AgentTypeSectionsResponse | null>(null);
  const [sections, setSections] = useState<SectionWithOrder[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState('');
  const [hasChanges, setHasChanges] = useState(false);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    setError('');
    try {
      const response = await profileSectionsService.getSectionsForAgentType(agentTypeId, false);
      setData(response);
      setSections(response.sections as SectionWithOrder[]);
      setHasChanges(false);
    } catch (err) {
      const errorMessage = getErrorMessage(err);
      setError(errorMessage);
      if (errorMessage.includes('Unauthorized')) {
        router.push('/login');
      }
    } finally {
      setIsLoading(false);
    }
  }, [agentTypeId, router]);

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

  const handleDragStart = (index: number) => {
    setDraggedIndex(index);
  };

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault();
    if (draggedIndex === null || draggedIndex === index) return;

    const newSections = [...sections];
    const draggedItem = newSections[draggedIndex];
    newSections.splice(draggedIndex, 1);
    newSections.splice(index, 0, draggedItem);

    // Update effective sort orders
    newSections.forEach((section, idx) => {
      section.effectiveSortOrder = idx;
    });

    setSections(newSections);
    setDraggedIndex(index);
    setHasChanges(true);
  };

  const handleDragEnd = () => {
    setDraggedIndex(null);
  };

  const moveSection = (index: number, direction: 'up' | 'down') => {
    const newIndex = direction === 'up' ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= sections.length) return;

    const newSections = [...sections];
    const temp = newSections[index];
    newSections[index] = newSections[newIndex];
    newSections[newIndex] = temp;

    // Update effective sort orders
    newSections.forEach((section, idx) => {
      section.effectiveSortOrder = idx;
    });

    setSections(newSections);
    setHasChanges(true);
  };

  const toggleRequired = (index: number) => {
    const newSections = [...sections];
    newSections[index] = {
      ...newSections[index],
      isRequired: !newSections[index].isRequired,
    };
    setSections(newSections);
    setHasChanges(true);
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError('');
    try {
      const sectionOrders: SectionOrderItem[] = sections.map((section, index) => ({
        sectionId: section.id,
        sortOrder: index,
        isRequired: section.isRequired,
      }));
      await profileSectionsService.updateSectionOrderForAgentType(agentTypeId, sectionOrders);
      setHasChanges(false);
      // Refresh to get updated hasCustomOrder flags
      await fetchData();
    } catch (err) {
      setError(getErrorMessage(err));
    } finally {
      setIsSaving(false);
    }
  };

  const handleReset = () => {
    fetchData();
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#f5a623]"></div>
      </div>
    );
  }

  return (
    <div>
      {/* Breadcrumb */}
      <div className="mb-6">
        <nav className="flex items-center space-x-2 text-sm text-[#666666]">
          <Link href="/dashboard/agent-types" className="hover:text-[#f5a623]">
            Agent Types
          </Link>
          <span>/</span>
          <span className="text-[#00293d] font-medium">{data?.agentType.name || 'Loading...'}</span>
          <span>/</span>
          <span className="text-[#00293d]">Sections</span>
        </nav>
      </div>

      {/* Page Title */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-[#00293d] font-fractul">
          Manage Sections for {data?.agentType.name}
        </h1>
        <p className="text-[#666666] font-serif">
          Customize the order and requirements of profile sections for this agent type.
          Drag to reorder or use the arrow buttons.
        </p>
      </div>

      {/* Sections List */}
      <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">
              <span className="text-sm text-[#666666]">
                {sections.length} section{sections.length !== 1 ? 's' : ''}
              </span>
              {hasChanges && (
                <span className="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">
                  Unsaved Changes
                </span>
              )}
            </div>
            <div className="flex space-x-3">
              {hasChanges && (
                <>
                  <button
                    onClick={handleReset}
                    disabled={isSaving}
                    className="px-4 py-2 border border-[#e5e7eb] text-[#00293d] rounded-xl hover:bg-[#f5f9f8] transition-colors disabled:opacity-50"
                  >
                    Reset
                  </button>
                  <button
                    onClick={handleSave}
                    disabled={isSaving}
                    className="px-4 py-2 bg-[#f5a623] text-white rounded-xl hover:bg-[#e09620] transition-colors disabled:opacity-50 flex items-center"
                  >
                    {isSaving ? (
                      <>
                        <svg className="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                        </svg>
                        Saving...
                      </>
                    ) : (
                      'Save Order'
                    )}
                  </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>
        )}

        {sections.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] font-serif">No sections assigned to this agent type</p>
            <Link
              href="/dashboard/profile-sections"
              className="mt-4 inline-block px-4 py-2 bg-[#f5a623] hover:bg-[#e09620] text-white text-sm font-medium rounded-lg transition-colors"
            >
              Go to Profile Sections
            </Link>
          </div>
        ) : (
          <div className="p-4 space-y-3">
            {sections.map((section, index) => (
              <div
                key={section.id}
                draggable
                onDragStart={() => handleDragStart(index)}
                onDragOver={(e) => handleDragOver(e, index)}
                onDragEnd={handleDragEnd}
                className={`bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-4 flex items-center justify-between hover:shadow-md cursor-move transition-all ${
                  draggedIndex === index ? 'ring-2 ring-[#f5a623]/30 ring-offset-2 shadow-lg' : ''
                }`}
              >
                <div className="flex items-center space-x-4">
                  {/* Drag Handle */}
                  <div className="text-[#9ca3af] cursor-grab">
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M8 6a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm0 6a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm0 6a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm8-12a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm0 6a2 2 0 1 1-4 0 2 2 0 0 1 4 0zm0 6a2 2 0 1 1-4 0 2 2 0 0 1 4 0z" />
                    </svg>
                  </div>

                  {/* Order Number */}
                  <div className="w-8 h-8 flex items-center justify-center rounded-full bg-[#e8f0ee] text-[#666666] text-sm font-medium">
                    {index + 1}
                  </div>

                  {/* Section Info */}
                  <div>
                    <div className="flex items-center space-x-2">
                      <span className="font-medium text-[#00293d]">{section.name}</span>
                      {section.isGlobal && (
                        <span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-[#fff7ed] text-[#f5a623]">
                          Global
                        </span>
                      )}
                      {section.isSystem && (
                        <span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-[#e8f0ee] text-[#5ba4a4]">
                          System
                        </span>
                      )}
                      {section.hasCustomOrder && (
                        <span className="px-2 py-0.5 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">
                          Custom Order
                        </span>
                      )}
                    </div>
                    <div className="text-sm text-[#666666]">
                      {section.description || 'No description'}
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-4">
                  {/* Required Toggle */}
                  <label className="flex items-center space-x-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={section.isRequired}
                      onChange={() => toggleRequired(index)}
                      className="rounded border-[#e5e7eb] text-[#f5a623] focus:ring-0"
                    />
                    <span className="text-sm text-[#666666]">Required</span>
                  </label>

                  {/* Move Buttons */}
                  <div className="flex space-x-1">
                    <button
                      onClick={() => moveSection(index, 'up')}
                      disabled={index === 0}
                      className="p-1.5 text-[#9ca3af] hover:text-[#666666] hover:bg-[#e8f0ee] rounded disabled:opacity-30 disabled:cursor-not-allowed"
                      title="Move up"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                      </svg>
                    </button>
                    <button
                      onClick={() => moveSection(index, 'down')}
                      disabled={index === sections.length - 1}
                      className="p-1.5 text-[#9ca3af] hover:text-[#666666] hover:bg-[#e8f0ee] rounded disabled:opacity-30 disabled:cursor-not-allowed"
                      title="Move down"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Info Box */}
      <div className="mt-6 p-4 bg-[#f5f9f8] rounded-xl border border-[#e5e7eb]">
        <h3 className="text-sm font-semibold text-[#00293d] mb-2 font-fractul">How Section Ordering Works</h3>
        <ul className="text-sm text-[#666666] space-y-1 font-serif">
          <li><strong>Global sections</strong> (purple badge) are automatically included for all agent types.</li>
          <li><strong>System sections</strong> (blue badge) cannot be deleted, only hidden.</li>
          <li><strong>Custom Order</strong> (yellow badge) indicates this agent type has a custom order for that section.</li>
          <li>Drag sections or use the arrow buttons to change the display order.</li>
          <li>Mark sections as <strong>Required</strong> to enforce completion by agents.</li>
          <li>Click <strong>Save Order</strong> to apply your changes.</li>
        </ul>
      </div>
    </div>
  );
}
