import { useState, FormEvent } from 'react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import api from '../../lib/api';
import { Term, WordType, CefrLevel } from '../../types/term';
import { toast } from 'sonner';

interface TermFormProps {
  term?: Term;
  onSuccess: () => void;
  onCancel: () => void;
}

export function TermForm({ term, onSuccess, onCancel }: TermFormProps) {
  const [formData, setFormData] = useState({
    wordText: term?.wordText || '',
    wordType: term?.wordType || WordType.NOUN,
    cefrLevel: term?.cefrLevel || CefrLevel.A1,
    shortDescription: term?.shortDescription || '',
    tags: term?.tags || '',
    iconAssetId: term?.iconAssetId || '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    
    if (!formData.wordText.trim()) {
      toast.error('Riječ je obavezna');
      return;
    }

    try {
      setIsSubmitting(true);
      
      if (term) {
        // Update existing term
        await api.put(`/api/terms/${term.id}`, formData);
        toast.success('Riječ uspješno ažurirana');
      } else {
        // Create new term
        await api.post('/api/terms', formData);
        toast.success('Riječ uspješno dodana');
      }
      
      onSuccess();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Greška pri spremanju');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label htmlFor="wordText">Riječ *</Label>
        <Input
          id="wordText"
          type="text"
          value={formData.wordText}
          onChange={(e) => setFormData({ ...formData, wordText: e.target.value })}
          placeholder="npr. Dobar dan"
          required
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <Label htmlFor="wordType">Vrsta riječi *</Label>
          <select
            id="wordType"
            value={formData.wordType}
            onChange={(e) => setFormData({ ...formData, wordType: e.target.value as WordType })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            required
          >
            <option value={WordType.NOUN}>Imenica</option>
            <option value={WordType.VERB}>Glagol</option>
            <option value={WordType.ADJECTIVE}>Pridjev</option>
            <option value={WordType.ADVERB}>Prilog</option>
            <option value={WordType.PRONOUN}>Zamjenica</option>
            <option value={WordType.PREPOSITION}>Prijedlog</option>
            <option value={WordType.CONJUNCTION}>Veznik</option>
            <option value={WordType.INTERJECTION}>Uzvik</option>
            <option value={WordType.PHRASE}>Fraza</option>
            <option value={WordType.OTHER}>Ostalo</option>
          </select>
        </div>

        <div>
          <Label htmlFor="cefrLevel">CEFR razina *</Label>
          <select
            id="cefrLevel"
            value={formData.cefrLevel}
            onChange={(e) => setFormData({ ...formData, cefrLevel: e.target.value as CefrLevel })}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            required
          >
            <option value={CefrLevel.A1}>A1</option>
            <option value={CefrLevel.A2}>A2</option>
            <option value={CefrLevel.B1}>B1</option>
            <option value={CefrLevel.B2}>B2</option>
            <option value={CefrLevel.C1}>C1</option>
            <option value={CefrLevel.C2}>C2</option>
          </select>
        </div>
      </div>

      <div>
        <Label htmlFor="shortDescription">Kratak opis</Label>
        <textarea
          id="shortDescription"
          value={formData.shortDescription}
          onChange={(e) => setFormData({ ...formData, shortDescription: e.target.value })}
          placeholder="Kratak opis značenja riječi"
          className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
          rows={3}
        />
      </div>

      <div>
        <Label htmlFor="tags">Oznake (odvojene zarezom)</Label>
        <Input
          id="tags"
          type="text"
          value={formData.tags}
          onChange={(e) => setFormData({ ...formData, tags: e.target.value })}
          placeholder="npr. pozdrav, osnovno"
        />
      </div>

      <div>
        <Label htmlFor="iconAssetId">ID ikone (opcionalno)</Label>
        <Input
          id="iconAssetId"
          type="text"
          value={formData.iconAssetId}
          onChange={(e) => setFormData({ ...formData, iconAssetId: e.target.value })}
          placeholder="npr. icon-123"
        />
      </div>

      <div className="flex gap-2 justify-end">
        <Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting}>
          Odustani
        </Button>
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? 'Spremanje...' : term ? 'Ažuriraj' : 'Dodaj'}
        </Button>
      </div>
    </form>
  );
}

