'use client';

import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

type SpanLabelType = {
  id: number;
  name: string;
  display_name: string;
  color: string;
  hotkey: string | null;
  is_active: boolean;
  sort_order: number;
  created_at: number;
};

export default function SpanLabelTypesPage() {
  const [types, setTypes] = useState<SpanLabelType[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);

  // Form state
  const [formData, setFormData] = useState({
    name: '',
    display_name: '',
    color: '#2196F3',
    hotkey: '',
    sort_order: 0,
  });

  const fetchTypes = async () => {
    try {
      const res = await fetch('/api/span-label-types');
      if (res.ok) {
        const data = await res.json();
        setTypes(data);
      }
    } catch (error) {
      console.error('Error fetching span label types:', error);
    } finally {
      setLoading(false);
    }
  };

  const seedDefaultTypes = async () => {
    const defaultTypes = [
      { name: 'bull_flag', display_name: 'Bull Flag', color: '#4CAF50', hotkey: '1', sort_order: 1 },
      { name: 'bear_flag', display_name: 'Bear Flag', color: '#F44336', hotkey: '2', sort_order: 2 },
      { name: 'triangle', display_name: 'Triangle', color: '#FF9800', hotkey: '3', sort_order: 3 },
      { name: 'wedge', display_name: 'Wedge', color: '#9C27B0', hotkey: '4', sort_order: 4 },
      { name: 'channel', display_name: 'Channel', color: '#2196F3', hotkey: '5', sort_order: 5 },
      { name: 'consolidation', display_name: 'Consolidation', color: '#607D8B', hotkey: '6', sort_order: 6 },
    ];

    try {
      for (const type of defaultTypes) {
        await fetch('/api/span-label-types', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(type),
        });
      }
      fetchTypes();
    } catch (error) {
      console.error('Error seeding types:', error);
    }
  };

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

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

    try {
      if (editingId !== null) {
        // Update existing type
        const res = await fetch(`/api/span-label-types/${editingId}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData),
        });

        if (res.ok) {
          setEditingId(null);
          resetForm();
          fetchTypes();
        } else {
          const error = await res.json();
          alert(error.error || 'Failed to update type');
        }
      } else {
        // Create new type
        const res = await fetch('/api/span-label-types', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData),
        });

        if (res.ok) {
          setShowAddForm(false);
          resetForm();
          fetchTypes();
        } else {
          const error = await res.json();
          alert(error.error || 'Failed to create type');
        }
      }
    } catch (error) {
      console.error('Error saving type:', error);
      alert('Failed to save type');
    }
  };

  const handleEdit = (type: SpanLabelType) => {
    setFormData({
      name: type.name,
      display_name: type.display_name,
      color: type.color,
      hotkey: type.hotkey || '',
      sort_order: type.sort_order,
    });
    setEditingId(type.id);
    setShowAddForm(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this span label type?')) {
      return;
    }

    try {
      const res = await fetch(`/api/span-label-types/${id}`, {
        method: 'DELETE',
      });

      if (res.ok) {
        fetchTypes();
      } else {
        const error = await res.json();
        alert(error.error || 'Failed to delete type');
      }
    } catch (error) {
      console.error('Error deleting type:', error);
      alert('Failed to delete type');
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      display_name: '',
      color: '#2196F3',
      hotkey: '',
      sort_order: 0,
    });
    setEditingId(null);
  };

  const handleCancel = () => {
    setShowAddForm(false);
    resetForm();
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-6xl mx-auto">
          <p>Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-6xl mx-auto">
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Span Label Types</h1>
            <p className="text-gray-600 mt-1">Manage pattern labels for span annotations</p>
          </div>
          <div className="flex gap-2">
            <Button onClick={() => window.location.href = '/'} variant="outline">
              Back to Chart
            </Button>
            {types.length === 0 && (
              <Button onClick={seedDefaultTypes}>
                Seed Default Types
              </Button>
            )}
            {!showAddForm && (
              <Button onClick={() => setShowAddForm(true)}>
                Add New Type
              </Button>
            )}
          </div>
        </div>

        {showAddForm && (
          <div className="bg-white p-6 rounded-lg shadow mb-6">
            <h2 className="text-xl font-semibold mb-4">
              {editingId !== null ? 'Edit Span Label Type' : 'Add New Span Label Type'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Internal Name *
                  </label>
                  <Input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="e.g., bull_flag"
                    required
                    disabled={editingId !== null}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Used internally (cannot be changed after creation)
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Display Name *
                  </label>
                  <Input
                    type="text"
                    value={formData.display_name}
                    onChange={(e) => setFormData({ ...formData, display_name: e.target.value })}
                    placeholder="e.g., Bull Flag"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Color *
                  </label>
                  <div className="flex gap-2">
                    <Input
                      type="color"
                      value={formData.color}
                      onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                      className="w-20"
                      required
                    />
                    <Input
                      type="text"
                      value={formData.color}
                      onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                      placeholder="#2196F3"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Hotkey
                  </label>
                  <Input
                    type="text"
                    value={formData.hotkey}
                    onChange={(e) => setFormData({ ...formData, hotkey: e.target.value })}
                    placeholder="e.g., 1, 2, 3"
                    maxLength={1}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Single key for quick assignment (optional)
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Sort Order
                  </label>
                  <Input
                    type="number"
                    value={formData.sort_order}
                    onChange={(e) => setFormData({ ...formData, sort_order: parseInt(e.target.value) || 0 })}
                    placeholder="0"
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    Lower numbers appear first
                  </p>
                </div>
              </div>

              <div className="flex gap-2">
                <Button type="submit">
                  {editingId !== null ? 'Update' : 'Create'}
                </Button>
                <Button type="button" variant="outline" onClick={handleCancel}>
                  Cancel
                </Button>
              </div>
            </form>
          </div>
        )}

        <div className="bg-white rounded-lg shadow overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Display Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Color
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Hotkey
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Sort Order
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {types.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-8 text-center text-gray-500">
                    No span label types found. Click "Seed Default Types" to get started.
                  </td>
                </tr>
              ) : (
                types.map((type) => (
                  <tr key={type.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {type.name}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {type.display_name}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm">
                      <div className="flex items-center gap-2">
                        <div
                          className="w-6 h-6 rounded border border-gray-300"
                          style={{ backgroundColor: type.color }}
                        />
                        <span className="text-gray-600">{type.color}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">
                      {type.hotkey || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                      {type.sort_order}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm">
                      <span
                        className={`px-2 py-1 text-xs font-medium rounded-full ${
                          type.is_active
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {type.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(type)}
                        >
                          Edit
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleDelete(type.id)}
                        >
                          Delete
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
