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

interface Currency {
  id: string;
  code: string;
  name: string;
  symbol: string;
  is_default: boolean;
}

export function SettingsCurrenciesPage() {
  const { t } = useTranslation();
  const [currencies, setCurrencies] = useState<Currency[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<Currency | null>(null);
  const [formData, setFormData] = useState({ code: '', name: '', symbol: '', is_default: false });

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

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

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

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

  const handleEdit = (c: Currency) => {
    setEditing(c);
    setFormData({ code: c.code, name: c.name, symbol: c.symbol, is_default: c.is_default });
    setShowForm(true);
  };

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

  return (
    <div className="space-y-6" data-testid="settings-currencies">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-secondary-900">{t('currencies.title')}</h1>
        <button
          onClick={() => { setEditing(null); setFormData({ code: '', name: '', symbol: '', is_default: false }); setShowForm(true); }}
          className="px-4 py-2 text-sm font-medium text-white bg-primary-600 rounded-lg hover:bg-primary-700"
        >
          {t('currencies.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 className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-secondary-700">{t('currencies.code')}</label>
              <input type="text" value={formData.code} onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase() })} maxLength={3} required disabled={!!editing} className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm disabled:bg-secondary-100" />
            </div>
            <div>
              <label className="block text-sm font-medium text-secondary-700">{t('currencies.symbol')}</label>
              <input type="text" value={formData.symbol} onChange={(e) => setFormData({ ...formData, symbol: e.target.value })} maxLength={5} required className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-secondary-700">{t('currencies.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>
          <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('currencies.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('currencies.code')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('currencies.name')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('currencies.symbol')}</th>
              <th className="px-4 py-2 text-left text-xs font-medium text-secondary-500 uppercase">{t('currencies.isDefault')}</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-secondary-200">
            {currencies.map((c) => (
              <tr key={c.id}>
                <td className="px-4 py-2 text-sm text-secondary-900">{c.code}</td>
                <td className="px-4 py-2 text-sm text-secondary-900">{c.name}</td>
                <td className="px-4 py-2 text-sm text-secondary-900">{c.symbol}</td>
                <td className="px-4 py-2 text-sm">{c.is_default && <span className="text-primary-600">✓</span>}</td>
                <td className="px-4 py-2 text-sm text-right">
                  <button onClick={() => handleEdit(c)} className="text-secondary-600 hover:underline mr-3">{t('common.edit')}</button>
                  <button onClick={() => handleDelete(c.id)} className="text-red-600 hover:underline">{t('common.delete')}</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
