import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus, X } from 'lucide-react';
import { Button, Input } from '../ui';
import type { CreateCategoryRequest } from '../../types';

interface AddCategorySectionProps {
  showForm: boolean;
  onToggle: () => void;
  onCreate: (data: CreateCategoryRequest) => Promise<void>;
}

export function AddCategorySection({ showForm, onToggle, onCreate }: AddCategorySectionProps) {
  const { t } = useTranslation();
  const [name, setName] = useState('');
  const [limitAmount, setLimitAmount] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!name || !limitAmount) return;

    try {
      setIsSubmitting(true);
      await onCreate({
        name,
        limit_amount: parseFloat(limitAmount),
      });
      setName('');
      setLimitAmount('');
      onToggle();
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="glass-effect rounded-2xl shadow-lg p-6">
      {!showForm ? (
        <button
          onClick={onToggle}
          className="w-full flex items-center justify-center gap-3 py-4 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white font-semibold rounded-xl transition-all duration-300 group"
        >
          <Plus className="w-6 h-6 group-hover:scale-110 transition-transform" />
          <span>{t('category.add')}</span>
        </button>
      ) : (
        <div className="space-y-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-xl font-bold text-gray-900">{t('category.add')}</h3>
            <button
              onClick={onToggle}
              className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
            >
              <X className="w-5 h-5 text-gray-600" />
            </button>
          </div>
          <Input
            type="text"
            placeholder={t('category.name')}
            value={name}
            onChange={(e) => setName(e.target.value)}
            fullWidth
          />
          <Input
            type="number"
            placeholder={t('category.limit')}
            value={limitAmount}
            onChange={(e) => setLimitAmount(e.target.value)}
            fullWidth
          />
          <div className="flex gap-3">
            <Button
              variant="success"
              fullWidth
              onClick={handleSubmit}
              disabled={isSubmitting || !name || !limitAmount}
            >
              {t('common.save')}
            </Button>
            <Button
              variant="secondary"
              fullWidth
              onClick={onToggle}
              disabled={isSubmitting}
            >
              {t('common.cancel')}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
