import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { apiGet, apiPost, apiPatch, apiDelete } from '@/api/client';

interface TaxRate {
  id: string;
  name: string;
  rate: number;
  is_default: boolean;
  country: string | null;
}

export function SettingsTaxesPage() {
  const { t } = useTranslation();
  const [taxes, setTaxes] = useState<TaxRate[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<TaxRate | null>(null);
  const [formData, setFormData] = useState({ name: '', rate: 0, is_default: false, country: '' });

  const fetchTaxes = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await apiGet<{ items: TaxRate[]; total: number }>('/taxes');
      setTaxes(data.items);
    } catch (err: any) {
      setError(err.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  }, [t]);

  React.useEffect(() => { fetchTaxes(); }, [fetchTaxes]);

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const payload = { ...formData, country: formData.country || null };
      if (editing) {
        await apiPatch(`/taxes/${editing.id}`, payload);
      } else {
        await apiPost('/taxes', payload);
      }
      setShowForm(false);
      setEditing(null);
      setFormData({ name: '', rate: 0, is_default: false, country: '' });
      await fetchTaxes();
    } catch (err: any) {
      setError(err.message || t('common.error'));
    }
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm(t('taxes.confirmDelete'))) return;
    try {
      await apiDelete(`/taxes/${id}`);
      await fetchTaxes();
    } catch (err: any) {
      setError(err.message || t('common.error'));
    }
  };

  const handleEdit = (tax: TaxRate) => {
    setEditing(tax);
    setFormData({ name: tax.name, rate: tax.rate, is_default: tax.is_default, country: tax.country || '' });
    setShowForm(true);
  };

  if (loading) return <div className="text-secondary-500">{t('common.loading')}</div>;

  return (
    <div className="space-y-6" data-testid="settings-taxes">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-secondary-900">{t('taxes.title')}</h1>
        <button
          onClick={() => { setEditing(null); setFormData({ name: '', rate: 0, is_default: false, country: '' }); setShowForm(true); }}
          className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700"
        >
          {t('taxes.add')}
        </button>
      </div>

      {error && <div className="p-3 text-sm text-red-700 bg-red-50 rounded-lg">{error}</div>}

      {showForm && (
        <form onSubmit={handleSave} className="p-4 border border-secondary-200 rounded-lg space-y-3">
          <div>
            <label className="block text-sm font-medium text-secondary-700">{t('taxes.name')}</label>
            <input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} required className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-secondary-700">{t('taxes.rate')} (%)</label>
              <input type="number" step="0.01" value={formData.rate} onChange={(e) => setFormData({ ...formData, rate: parseFloat(e.target.value) || 0 })} required className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
            </div>
            <div>
              <label className="block text-sm font-medium text-secondary-700">{t('taxes.country')}</label>
              <input type="text" value={formData.country} onChange={(e) => setFormData({ ...formData, country: e.target.value })} maxLength={2} placeholder="DE" className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
            </div>
          </div>
          <label className="flex items-center gap-2 text-sm font-medium text-secondary-700">
            <input type="checkbox" checked={formData.is_default} onChange={(e) => setFormData({ ...formData, is_default: e.target.checked })} />
            {t('taxes.isDefault')}
          </label>
          <div className="flex justify-end gap-2">
            <button type="button" onClick={() => { setShowForm(false); setEditing(null); }} className="px-3 py-1.5 text-sm font-medium text-secondary-700 bg-secondary-100 rounded-lg hover:bg-secondary-200">{t('common.cancel')}</button>
            <button type="submit" className="px-3 py-1.5 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700">{t('common.save')}</button>
          </div>
        </form>
      )}

      <div className="overflow-hidden border border-secondary-200 rounded-lg">
        <table className="min-w-full divide-y divide-secondary-200">
          <thead className="bg-secondary-50">
            <tr>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('taxes.name')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('taxes.rate')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('taxes.isDefault')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('taxes.country')}</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-secondary-200">
            {taxes.map((tax) => (
              <tr key={tax.id}>
                <td className="px-4 py-2 text-sm text-secondary-900">{tax.name}</td>
                <td className="px-4 py-2 text-sm text-secondary-900">{tax.rate}%</td>
                <td className="px-4 py-2 text-sm">{tax.is_default && <span className="text-primary-600">✓</span>}</td>
                <td className="px-4 py-2 text-sm text-secondary-900">{tax.country || '—'}</td>
                <td className="px-4 py-2 text-sm text-right">
                  <button onClick={() => handleEdit(tax)} className="text-secondary-600 hover:underline mr-3">{t('common.edit')}</button>
                  <button onClick={() => handleDelete(tax.id)} className="text-red-600 hover:underline">{t('common.delete')}</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
