'use client';

import { useState, useEffect } from 'react';
import { Tag, TagAlias } from '../../types/api';
import { tagApi } from '../../lib/api';
import { Input, Textarea } from '../ui/Input';
import Button from '../ui/Button';
import ColorPicker from '../ui/ColorPicker';

interface TagEditModalProps {
  tag?: Tag;
  isOpen: boolean;
  onClose: () => void;
  onSave: (tag: Tag) => void;
  onDelete?: (tag: Tag) => void;
}

export default function TagEditModal({ tag, isOpen, onClose, onSave, onDelete }: TagEditModalProps) {
  const [formData, setFormData] = useState({
    name: '',
    color: '',
    description: ''
  });
  const [aliases, setAliases] = useState<TagAlias[]>([]);
  const [newAlias, setNewAlias] = useState('');
  const [loading, setSaving] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [deleteConfirm, setDeleteConfirm] = useState(false);

  // Reset form when modal opens/closes or tag changes
  useEffect(() => {
    if (isOpen && tag) {
      setFormData({
        name: tag.name || '',
        color: tag.color || '',
        description: tag.description || ''
      });
      setAliases(tag.aliases || []);
    } else if (isOpen && !tag) {
      // New tag
      setFormData({
        name: '',
        color: '',
        description: ''
      });
      setAliases([]);
    }
    setNewAlias('');
    setErrors({});
    setDeleteConfirm(false);
  }, [isOpen, tag]);

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleAddAlias = async () => {
    if (!newAlias.trim() || !tag) return;
    
    try {
      // Check if alias already exists
      if (aliases.some(alias => alias.aliasName.toLowerCase() === newAlias.toLowerCase())) {
        setErrors({ alias: 'This alias already exists for this tag' });
        return;
      }

      // Create alias via API
      const newAliasData = await tagApi.addAlias(tag.id, newAlias.trim());
      setAliases(prev => [...prev, newAliasData]);
      setNewAlias('');
      setErrors(prev => ({ ...prev, alias: '' }));
    } catch (error) {
      setErrors({ alias: 'Failed to add alias' });
    }
  };

  const handleRemoveAlias = async (aliasId: string) => {
    if (!tag) return;

    try {
      await tagApi.removeAlias(tag.id, aliasId);
      setAliases(prev => prev.filter(alias => alias.id !== aliasId));
    } catch (error) {
      console.error('Failed to remove alias:', error);
    }
  };

  const handleSave = async () => {
    setErrors({});
    setSaving(true);

    try {
      const payload = {
        name: formData.name.trim(),
        color: formData.color || undefined,
        description: formData.description || undefined
      };

      let savedTag: Tag;

      if (tag) {
        // Update existing tag
        savedTag = await tagApi.updateTag(tag.id, payload);
      } else {
        // Create new tag
        savedTag = await tagApi.createTag(payload);
      }

      // Include aliases in the saved tag
      savedTag.aliases = aliases;
      onSave(savedTag);
      onClose();
    } catch (error: any) {
      setErrors({ submit: error.message });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!tag || !onDelete) return;

    try {
      setSaving(true);
      await tagApi.deleteTag(tag.id);
      onDelete(tag);
      onClose();
    } catch (error: any) {
      const errorMessage = error.response?.data?.error || error.message || 'Failed to delete tag';
      setErrors({ submit: errorMessage });
    } finally {
      setSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6 border-b theme-border">
          <h2 className="text-xl font-semibold theme-header">
            {tag ? `Edit Tag: "${tag.name}"` : 'Create New Tag'}
          </h2>
        </div>

        <div className="p-6 space-y-6">
          {/* Basic Information */}
          <div className="space-y-4">
            <Input
              label="Tag Name"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              error={errors.name}
              disabled={loading}
              placeholder="Enter tag name"
              required
            />

            <ColorPicker
              label="Color (Optional)"
              value={formData.color}
              onChange={(color) => handleInputChange('color', color || '')}
              disabled={loading}
            />

            <Textarea
              label="Description (Optional)"
              value={formData.description}
              onChange={(e) => handleInputChange('description', e.target.value)}
              error={errors.description}
              disabled={loading}
              placeholder="Optional description for this tag"
              rows={3}
            />
          </div>

          {/* Aliases Section (only for existing tags) */}
          {tag && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium theme-header">
                Aliases ({aliases.length})
              </h3>
              
              {aliases.length > 0 && (
                <div className="space-y-2 max-h-32 overflow-y-auto border theme-border rounded-lg p-3">
                  {aliases.map((alias) => (
                    <div key={alias.id} className="flex items-center justify-between py-1">
                      <span className="text-sm theme-text">
                        {alias.aliasName}
                        {alias.createdFromMerge && (
                          <span className="ml-2 text-xs theme-text-muted">(from merge)</span>
                        )}
                      </span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleRemoveAlias(alias.id)}
                        disabled={loading}
                        className="text-xs text-red-600 hover:text-red-800"
                      >
                        Remove
                      </Button>
                    </div>
                  ))}
                </div>
              )}

              <div className="flex gap-2">
                <Input
                  value={newAlias}
                  onChange={(e) => setNewAlias(e.target.value)}
                  placeholder="Add new alias"
                  error={errors.alias}
                  disabled={loading}
                  onKeyPress={(e) => e.key === 'Enter' && handleAddAlias()}
                />
                <Button
                  variant="secondary"
                  onClick={handleAddAlias}
                  disabled={loading || !newAlias.trim()}
                >
                  Add
                </Button>
              </div>
            </div>
          )}

          {/* Story Information (for existing tags) */}
          {tag && (
            <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
              <h3 className="text-sm font-medium theme-header mb-2">Usage Statistics</h3>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="theme-text-muted">Stories:</span>
                  <span className="ml-2 font-medium">{tag.storyCount || 0}</span>
                </div>
                <div>
                  <span className="theme-text-muted">Collections:</span>
                  <span className="ml-2 font-medium">{tag.collectionCount || 0}</span>
                </div>
              </div>
              {tag.storyCount && tag.storyCount > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="mt-2 text-xs"
                  onClick={() => window.open(`/library?tags=${encodeURIComponent(tag.name)}`, '_blank')}
                >
                  View Stories →
                </Button>
              )}
            </div>
          )}

          {/* Error Display */}
          {errors.submit && (
            <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <p className="text-sm text-red-600 dark:text-red-400">{errors.submit}</p>
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="p-6 border-t theme-border flex justify-between">
          <div className="flex gap-2">
            {tag && onDelete && (
              <>
                {!deleteConfirm ? (
                  <Button
                    variant="ghost"
                    onClick={() => setDeleteConfirm(true)}
                    disabled={loading}
                    className="text-red-600 hover:text-red-800"
                  >
                    Delete Tag
                  </Button>
                ) : (
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      onClick={() => setDeleteConfirm(false)}
                      disabled={loading}
                      className="text-sm"
                    >
                      Cancel
                    </Button>
                    <Button
                      variant="ghost"
                      onClick={handleDelete}
                      disabled={loading}
                      className="text-sm bg-red-600 text-white hover:bg-red-700"
                    >
                      {loading ? 'Deleting...' : 'Confirm Delete'}
                    </Button>
                  </div>
                )}
              </>
            )}
          </div>
          
          <div className="flex gap-2">
            <Button
              variant="ghost"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              onClick={handleSave}
              disabled={loading || !formData.name.trim()}
            >
              {loading ? 'Saving...' : (tag ? 'Save Changes' : 'Create Tag')}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}