import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { apiGet, apiPost, apiPatch, apiDelete } from '@/api/client';

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

// ── Zod Schema ──
const taxSchema = z.object({
  name: z.string().min(1, 'required'),
  rate: z.coerce.number().min(0, 'invalidNumber').max(100, 'invalidNumber'),
  is_default: z.boolean().default(false),
  country: z.string().max(2, 'maxLength').optional().default(''),
});

type TaxFormData = z.infer<typeof taxSchema>;

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 {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<TaxFormData>({
    resolver: zodResolver(taxSchema),
    defaultValues: { 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 onSubmit = async (data: TaxFormData) => {
    try {
      const payload = { ...data, country: data.country || null };
      if (editing) {
        await apiPatch(`/taxes/${editing.id}`, payload);
      } else {
        await apiPost('/taxes', payload);
      }
      setShowForm(false);
      setEditing(null);
      reset({ 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);
    reset({ name: tax.name, rate: tax.rate, is_default: tax.is_default, country: tax.country || '' });
    setShowForm(true);
  };

  const handleNew = () => {
    setEditing(null);
    reset({ name: '', rate: 0, is_default: false, country: '' });
    setShowForm(true);
  };

  const errorMsg = (key: string | undefined) => {
    if (!key) return undefined;
    if (key === 'required') return t('validation.required');
    if (key === 'invalidNumber') return t('validation.invalidNumber', 'Invalid number');
    if (key === 'maxLength') return t('validation.maxLength', { count: 2 });
    return key;
  };

  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={handleNew}
          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={handleSubmit(onSubmit)} 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" {...register('name')} className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
            {errors.name && <p className="text-xs text-danger-600 mt-1">{errorMsg(errors.name.message)}</p>}
          </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" {...register('rate')} className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
              {errors.rate && <p className="text-xs text-danger-600 mt-1">{errorMsg(errors.rate.message)}</p>}
            </div>
            <div>
              <label className="block text-sm font-medium text-secondary-700">{t('taxes.country')}</label>
              <input type="text" {...register('country')} maxLength={2} placeholder="DE" className="mt-1 block w-full rounded-md border border-secondary-300 px-3 py-1.5 text-sm" />
              {errors.country && <p className="text-xs text-danger-600 mt-1">{errorMsg(errors.country.message)}</p>}
            </div>
          </div>
          <label className="flex items-center gap-2 text-sm font-medium text-secondary-700">
            <input type="checkbox" {...register('is_default')} />
            {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" disabled={isSubmitting} 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>
  );
}
