import React, { useState, useEffect } from 'react';
import type { Tag } from '@/types/types';
import { titlecase } from '@/lib/utils';

interface WordFormData {
  english: string;
  hindi: string;
  type: string;
  gender?: 'm' | 'f';
  note?: string;
  examples?: Array<{ english: string; hindi: string; note?: string }>;
  seeAlso?: Array<{ reference: string; note?: string }>;
}

export default function AddVocabForm() {
  const [tags, setTags] = useState<Tag[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [tagsLoading, setTagsLoading] = useState(true);
  const [message, setMessage] = useState('');
  const [showNewTag, setShowNewTag] = useState(false);
  const [newTagName, setNewTagName] = useState('');
  const [newTagDescription, setNewTagDescription] = useState('');
  const [formData, setFormData] = useState<WordFormData>({
    english: '',
    hindi: '',
    type: 'noun',
    gender: undefined,
    note: undefined,
    examples: undefined,
    seeAlso: undefined,
  });
  const englishInputRef = React.useRef<HTMLInputElement>(null);

  useEffect(() => {
    // Get URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const tagFromUrl = urlParams.get('tag');
    const typeFromUrl = urlParams.get('type');

    setTagsLoading(true);
    fetch('/api/tags.json')
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP error! status: ${res.status}`);
        }
        return res.json();
      })
      .then((data: Tag[]) => {
        if (Array.isArray(data) && data.length > 0) {
          setTags(data);

          // Use tag from URL if provided
          if (tagFromUrl) {
            const tag = data.find(t => t.name === tagFromUrl);
            if (tag) {
              setSelectedTagIds([tag.id]);
            }
          }

          // Use type from URL if provided
          if (typeFromUrl) {
            setFormData(prev => ({ ...prev, type: typeFromUrl }));
          }
        } else {
          setMessage('No tags found');
        }
      })
      .catch(err => {
        console.error('Failed to load tags:', err);
        setMessage(`Failed to load tags: ${err.message}`);
      })
      .finally(() => {
        setTagsLoading(false);
      });
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage('');

    try {
      // Build word object
      const word: any = {
        english: formData.english,
        hindi: formData.hindi,
        type: formData.type || null,
        gender: formData.gender || null,
        note: formData.note?.trim() || null,
        tagIds: selectedTagIds,
      };

      // Add examples if present
      if (formData.examples && formData.examples.length > 0) {
        const validExamples = formData.examples.filter(
          ex => ex.english.trim() || ex.hindi.trim()
        );
        if (validExamples.length > 0) {
          word.examples = validExamples;
        }
      }

      // Add see also if present
      if (formData.seeAlso && formData.seeAlso.length > 0) {
        const validSeeAlso = formData.seeAlso.filter(
          sa => sa.reference.trim()
        );
        if (validSeeAlso.length > 0) {
          word.seeAlso = validSeeAlso;
        }
      }

      const requestBody: any = word;

      // Include new tag information if creating one
      if (showNewTag) {
        requestBody.newTag = {
          name: newTagName,
          description: newTagDescription || null,
        };
      }

      const response = await fetch('/api/vocab.json', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });

      const result = await response.json();

      if (response.ok) {
        setMessage('Word added successfully!');

        // Remember the current type and tags for bulk entry
        const currentType = formData.type;
        const currentTagIds = showNewTag && result.word?.tags
          ? result.word.tags.map((t: Tag) => t.id)
          : selectedTagIds;

        // Update URL with current tag and type to persist through reloads
        const currentTagNames = showNewTag && result.word?.tags
          ? result.word.tags.map((t: Tag) => t.name)
          : tags.filter(t => selectedTagIds.includes(t.id)).map(t => t.name);

        if (currentTagNames.length > 0) {
          const newUrl = `${window.location.pathname}?tag=${currentTagNames[0]}&type=${currentType}`;
          window.history.replaceState({}, '', newUrl);
        }

        // Reset form but keep the type and tags
        setFormData({
          english: '',
          hindi: '',
          gender: undefined,
          type: currentType,
          note: '',
          examples: [],
          seeAlso: [],
        });

        // Focus back on English input for quick bulk entry
        setTimeout(() => {
          englishInputRef.current?.focus();
        }, 100);

        // If we created a new tag, refresh the tags list
        if (showNewTag) {
          setShowNewTag(false);
          setNewTagName('');
          setNewTagDescription('');

          // Refresh tags and select the new tag
          fetch('/api/tags.json')
            .then(res => res.json())
            .then((data: Tag[]) => {
              if (Array.isArray(data) && data.length > 0) {
                setTags(data);
                setSelectedTagIds(currentTagIds);
              }
            });
        } else {
          setSelectedTagIds(currentTagIds);
        }
      } else {
        setMessage(`Error: ${result.error}`);
      }
    } catch (error) {
      setMessage('Failed to add word');
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleTag = (tagId: number) => {
    setSelectedTagIds(prev =>
      prev.includes(tagId)
        ? prev.filter(id => id !== tagId)
        : [...prev, tagId]
    );
  };

  const addExample = () => {
    setFormData({
      ...formData,
      examples: [...(formData.examples || []), { english: '', hindi: '' }],
    });
  };

  const updateExample = (index: number, field: 'english' | 'hindi' | 'note', value: string) => {
    const newExamples = [...(formData.examples || [])];
    newExamples[index] = { ...newExamples[index], [field]: value };
    setFormData({ ...formData, examples: newExamples });
  };

  const removeExample = (index: number) => {
    const newExamples = (formData.examples || []).filter((_, i) => i !== index);
    setFormData({ ...formData, examples: newExamples });
  };

  const addSeeAlso = () => {
    setFormData({
      ...formData,
      seeAlso: [...(formData.seeAlso || []), { reference: '', note: '' }],
    });
  };

  const updateSeeAlso = (index: number, field: 'reference' | 'note', value: string) => {
    const newSeeAlso = [...(formData.seeAlso || [])];
    newSeeAlso[index] = { ...newSeeAlso[index], [field]: value };
    setFormData({ ...formData, seeAlso: newSeeAlso });
  };

  const removeSeeAlso = (index: number) => {
    const newSeeAlso = (formData.seeAlso || []).filter((_, i) => i !== index);
    setFormData({ ...formData, seeAlso: newSeeAlso });
  };

  return (
    <div className="vocab-form">
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <h3>Categories</h3>
          <div className="tag-checkboxes">
            {tags.map((tag) => (
              <label key={tag.id} className="tag-checkbox">
                <input
                  type="checkbox"
                  checked={selectedTagIds.includes(tag.id)}
                  onChange={() => toggleTag(tag.id)}
                />
                <span>{titlecase(tag.name)}</span>
              </label>
            ))}
          </div>
        </div>

        {showNewTag && (
          <>
            <div className="form-group new-word">
              <label htmlFor="newTagName">Name:</label>
              <input
                type="text"
                id="newTagName"
                value={newTagName}
                onChange={(e) => setNewTagName(e.target.value.toLowerCase().replace(/\s+/g, '-'))}
                placeholder="e.g., food-and-drink"
                required={showNewTag}
              />
            </div>
            <div className="form-group new-word">
              <label htmlFor="newTagDescription">Description:</label>
              <textarea
                id="newTagDescription"
                value={newTagDescription}
                onChange={(e) => setNewTagDescription(e.target.value)}
                rows={3}
                placeholder="e.g., Words related to food and beverages"
              />
            </div>
          </>
        )}
        <button type="button" onClick={() => setShowNewTag(!showNewTag)}>
          {showNewTag ? 'Cancel' : 'New Category'}
        </button>
        <h3>New Word</h3>
        <div className="form-group new-word">
          <label htmlFor="english">English:</label>
          <input
            type="text"
            id="english"
            ref={englishInputRef}
            value={formData.english}
            onChange={(e) => setFormData({ ...formData, english: e.target.value })}
            autoFocus
            required
          />
        </div>

        <div className="form-group new-word">
          <label htmlFor="hindi">Hindi:</label>
          <input
            type="text"
            id="hindi"
            value={formData.hindi}
            onChange={(e) => setFormData({ ...formData, hindi: e.target.value })}
            required
          />
        </div>

        <div className="form-group new-word">
          <label htmlFor="type">Type:</label>
          <select
            id="type"
            value={['noun', 'verb', 'adjective', 'adverb', 'pronoun', 'conjunction', 'preposition', 'interjection'].includes(formData.type) ? formData.type : 'custom'}
            onChange={(e) => {
              const value = e.target.value;
              if (value === 'custom') {
                const customValue = prompt('Enter custom type:', formData.type);
                if (customValue) {
                  setFormData({ ...formData, type: customValue });
                }
              } else {
                setFormData({ ...formData, type: value });
              }
            }}
          >
            <option value="noun">Noun</option>
            <option value="verb">Verb</option>
            <option value="adjective">Adjective</option>
            <option value="adverb">Adverb</option>
            <option value="pronoun">Pronoun</option>
            <option value="conjunction">Conjunction</option>
            <option value="preposition">Preposition</option>
            <option value="interjection">Interjection</option>
            <option value="custom">{['noun', 'verb', 'adjective', 'adverb', 'pronoun', 'conjunction', 'preposition', 'interjection'].includes(formData.type) ? 'Custom...' : `Custom: ${formData.type}`}</option>
          </select>
        </div>

        <div className="form-group new-word">
          <label htmlFor="gender">Gender:</label>
          <select
            id="gender"
            value={formData.gender ?? ''}
            onChange={(e) => {
              const value = e.target.value;
              setFormData({
                ...formData,
                gender: value === '' ? undefined : (value as 'm' | 'f')
              });
            }}
          >
            <option value="">N/A</option>
            <option value="m">Masculine (m)</option>
            <option value="f">Feminine (f)</option>
          </select>
        </div>

        <div className="form-group new-word">
          <label htmlFor="note">Note:</label>
          <textarea
            id="note"
            value={formData.note || ''}
            onChange={(e) => setFormData({ ...formData, note: e.target.value })}
            rows={3}
          />
        </div>

        <div className="form-group new-word">
          <label>Examples:</label>
          {formData.examples?.map((example, index) => (
            <div key={index} className="example-group">
              <input
                type="text"
                placeholder="English example"
                value={example.english}
                onChange={(e) => updateExample(index, 'english', e.target.value)}
              />
              <input
                type="text"
                placeholder="Hindi example"
                value={example.hindi}
                onChange={(e) => updateExample(index, 'hindi', e.target.value)}
              />
              <input
                type="text"
                placeholder="Note (optional)"
                value={example.note || ''}
                onChange={(e) => updateExample(index, 'note', e.target.value)}
              />
              <button type="button" onClick={() => removeExample(index)}>
                Remove
              </button>
            </div>
          ))}
          <button type="button" onClick={addExample}>
            Add Example
          </button>
        </div>

        <div className="form-group new-word">
          <label>See Also:</label>
          {formData.seeAlso?.map((seeAlso, index) => (
            <div key={index} className="see-also-group">
              <input
                type="text"
                placeholder="Reference (e.g., [text](#link))"
                value={seeAlso.reference}
                onChange={(e) => updateSeeAlso(index, 'reference', e.target.value)}
              />
              <input
                type="text"
                placeholder="Note (optional)"
                value={seeAlso.note || ''}
                onChange={(e) => updateSeeAlso(index, 'note', e.target.value)}
              />
              <button type="button" onClick={() => removeSeeAlso(index)}>
                Remove
              </button>
            </div>
          ))}
          <button type="button" onClick={addSeeAlso}>
            Add Reference
          </button>
        </div>

        <button type="submit" disabled={loading}>
          {loading ? 'Adding...' : 'Add Word'}
        </button>
      </form>

      {message && (
        <div className={`message ${message.includes('Error') ? 'error' : 'success'}`}>
          {message}
        </div>
      )}

      <style>{`
      .hidden { 
        display: none !important;
      }

        .vocab-form {
        font-size: 1rem;
          max-width: 600px;
          margin: 2rem 0;
          font-family: var(--font-sans);
        }

        .form-group.new-word {
          margin-bottom: 1.5rem;
          display: grid;
          grid-template-columns: 75px 1fr;
          align-items: baseline;
          gap: 1rem;
        }

        .new-word.form-group label {
          text-align: right;
          display: inline-block;
        }

        .form-group label {
          display: flex;
          gap: 0.5rem;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
          width: 100%;
          padding: 0.5rem;
          border: 1px solid var(--sl-color-gray-5);
          border-radius: 4px;
          background: var(--sl-color-bg);
          color: var(--sl-color-text);
        }

        .tag-checkboxes {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(175px, 1fr));
          margin-bottom: 0.5rem;
        }

        .form-group button {
          margin: 0;
          font-family: inherit;
          white-space: nowrap;
          width: min-content;
          padding: 0 1rem;
        }

        .tag-checkbox {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          font-weight: normal;
          margin-top: 0;
        }

        .tag-checkbox input[type="checkbox"] {
          width: auto;
        }

        .tag-desc {
          color: var(--sl-color-gray-3);
          font-size: 0.9em;
        }

        .example-group,
        .see-also-group {
          display: grid;
          grid-template-columns: 1fr 1fr 1fr auto;
          gap: 0.5rem;
          margin-bottom: 0.5rem;
        }

        .example-group input,
        .see-also-group input {
          width: auto;
        }

        button:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        button[type="button"] {
          background: var(--sl-color-gray-6);
          margin-right: 0.5rem;
        }

        .message {
          margin-top: 1rem;
          padding: 1rem;
          border-radius: 4px;
        }

        .message.success {
          background: var(--sl-color-green);
          color: white;
        }

        .message.error {
          background: var(--sl-color-red);
          color: white;
        }
      `}</style>
    </div>
  );
}
