'use client';

import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Edit, Loader2, Plus, Trash2 } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { apiClient } from '@/lib/api-client';

interface ExchangeRate {
  id: string;
  fromCurrency: string;
  toCurrency: string;
  rate: number;
  source: string;
  effectiveDate: string;
}

const CURRENCY_META: Record<string, { name: string }> = {
  ETB: { name: 'Ethiopian Birr' },
  DJF: { name: 'Djiboutian Franc' },
  USD: { name: 'US Dollar' },
};

const CURRENCY_OPTIONS = ['ETB', 'DJF', 'USD'];

export default function CurrenciesPage() {
  const [editingRate, setEditingRate]     = useState<ExchangeRate | null>(null);
  const [rateInput, setRateInput]         = useState('');
  const [error, setError]                 = useState<string | null>(null);
  const [showAddModal, setShowAddModal]   = useState(false);
  const [addForm, setAddForm]             = useState({ fromCurrency: 'ETB', toCurrency: 'DJF', rate: '' });
  const [deleteConfirm, setDeleteConfirm] = useState<ExchangeRate | null>(null);
  const queryClient = useQueryClient();

  const { data: rates = [], isLoading } = useQuery<ExchangeRate[]>({
    queryKey: ['currencies'],
    queryFn: () => apiClient.get('/currencies'),
    select: (d: any) => (Array.isArray(d) ? d : d?.data ?? d?.items ?? []),
  });

  const createMutation = useMutation({
    mutationFn: (data: any) => apiClient.post('/currencies', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['currencies'] });
      setShowAddModal(false);
      setAddForm({ fromCurrency: 'ETB', toCurrency: 'DJF', rate: '' });
      setError(null);
    },
    onError: (err: any) => setError(err.response?.data?.message || 'Failed to create rate'),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, rate }: { id: string; rate: number }) =>
      apiClient.patch(`/currencies/${id}`, { rate }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['currencies'] });
      setEditingRate(null);
      setError(null);
    },
    onError: (err: any) => setError(err.response?.data?.message || 'Failed to update rate'),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/currencies/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['currencies'] });
      setDeleteConfirm(null);
    },
    onError: (err: any) => setError(err.response?.data?.message || 'Failed to delete rate'),
  });

  const columns = [
    {
      key: 'pair',
      label: 'Pair',
      render: (r: ExchangeRate) => (
        <div className="flex items-center gap-2">
          <span className="font-mono font-semibold">{r.fromCurrency}</span>
          <span className="text-muted-foreground">→</span>
          <span className="font-mono font-semibold">{r.toCurrency}</span>
          <span className="text-xs text-muted-foreground ml-1">
            {CURRENCY_META[r.toCurrency]?.name ?? r.toCurrency}
          </span>
        </div>
      ),
    },
    {
      key: 'rate',
      label: 'Rate',
      render: (r: ExchangeRate) => (
        <div>
          <div className="font-mono font-semibold">
            1 {r.fromCurrency} = {r.rate} {r.toCurrency}
          </div>
          {r.rate > 0 && (
            <div className="text-xs text-muted-foreground">
              1 {r.toCurrency} = {(1 / r.rate).toFixed(6)} {r.fromCurrency}
            </div>
          )}
        </div>
      ),
    },
    {
      key: 'source',
      label: 'Source',
      render: (r: ExchangeRate) => (
        <span className="text-sm text-muted-foreground">{r.source ?? '—'}</span>
      ),
    },
    {
      key: 'effectiveDate',
      label: 'Effective Date',
      render: (r: ExchangeRate) => (
        <span className="text-sm text-muted-foreground">
          {r.effectiveDate ? new Date(r.effectiveDate).toLocaleDateString() : '—'}
        </span>
      ),
    },
  ];

  const actions = [
    {
      label: 'Edit',
      onClick: (r: ExchangeRate) => { setEditingRate(r); setRateInput(String(r.rate)); setError(null); },
      variant: 'secondary' as const,
      icon: Edit,
    },
    {
      label: 'Delete',
      onClick: (r: ExchangeRate) => setDeleteConfirm(r),
      variant: 'danger' as const,
      icon: Trash2,
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Exchange Rates</h1>
          <p className="text-muted-foreground mt-1">Manage currency exchange rates</p>
        </div>
        <ActionButton icon={Plus} onClick={() => { setError(null); setShowAddModal(true); }}>
          Add Rate
        </ActionButton>
      </div>

      {error && !editingRate && !showAddModal && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 rounded-lg text-sm text-red-800 dark:text-red-200">
          {error}
        </div>
      )}

      <div className="card">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : (
          <DataTable
            data={rates}
            columns={columns}
            actions={actions}
            loading={false}
            emptyMessage="No exchange rates configured."
          />
        )}
      </div>

      {/* Add Modal */}
      <Modal isOpen={showAddModal} onClose={() => { setShowAddModal(false); setError(null); }} title="Add Exchange Rate" size="sm">
        <div className="space-y-4">
          {error && (
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 p-3 rounded-lg text-sm text-red-800 dark:text-red-200">{error}</div>
          )}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="label">From *</label>
              <select className="input" value={addForm.fromCurrency} onChange={(e) => setAddForm({ ...addForm, fromCurrency: e.target.value })}>
                {CURRENCY_OPTIONS.map(c => <option key={c} value={c}>{c} — {CURRENCY_META[c]?.name ?? c}</option>)}
              </select>
            </div>
            <div>
              <label className="label">To *</label>
              <select className="input" value={addForm.toCurrency} onChange={(e) => setAddForm({ ...addForm, toCurrency: e.target.value })}>
                {CURRENCY_OPTIONS.map(c => <option key={c} value={c}>{c} — {CURRENCY_META[c]?.name ?? c}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="label">Rate (1 {addForm.fromCurrency} = ? {addForm.toCurrency}) *</label>
            <input type="number" min="0.000001" step="0.000001" className="input" placeholder="e.g., 3.25"
              value={addForm.rate} onChange={(e) => setAddForm({ ...addForm, rate: e.target.value })} />
          </div>
          <div className="flex gap-2 justify-end pt-2">
            <ActionButton variant="secondary" onClick={() => { setShowAddModal(false); setError(null); }}>Cancel</ActionButton>
            <ActionButton loading={createMutation.isPending} onClick={() => {
              if (addForm.fromCurrency === addForm.toCurrency) { setError('From and To currencies must differ'); return; }
              const rate = parseFloat(addForm.rate);
              if (isNaN(rate) || rate <= 0) { setError('Rate must be a positive number'); return; }
              createMutation.mutate({ fromCurrency: addForm.fromCurrency, toCurrency: addForm.toCurrency, rate });
            }}>
              Add Rate
            </ActionButton>
          </div>
        </div>
      </Modal>

      {/* Edit Modal */}
      <Modal isOpen={!!editingRate} onClose={() => { setEditingRate(null); setError(null); }} title={`Edit Rate — ${editingRate?.fromCurrency} → ${editingRate?.toCurrency}`} size="sm">
        <div className="space-y-4">
          {error && (
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 p-3 rounded-lg text-sm text-red-800 dark:text-red-200">{error}</div>
          )}
          <div>
            <label className="label">Rate (1 {editingRate?.fromCurrency} = ? {editingRate?.toCurrency})</label>
            <input type="number" min="0.000001" step="0.000001" className="input w-full"
              value={rateInput} onChange={(e) => setRateInput(e.target.value)} autoFocus />
            {rateInput && parseFloat(rateInput) > 0 && (
              <p className="text-xs text-muted-foreground mt-1">
                ≈ 1 {editingRate?.toCurrency} = {(1 / parseFloat(rateInput)).toFixed(6)} {editingRate?.fromCurrency}
              </p>
            )}
          </div>
          <div className="flex gap-2 justify-end pt-2">
            <ActionButton variant="secondary" onClick={() => { setEditingRate(null); setError(null); }}>Cancel</ActionButton>
            <ActionButton loading={updateMutation.isPending} onClick={() => {
              const rate = parseFloat(rateInput);
              if (isNaN(rate) || rate <= 0) { setError('Rate must be a positive number'); return; }
              updateMutation.mutate({ id: editingRate!.id, rate });
            }}>
              Save
            </ActionButton>
          </div>
        </div>
      </Modal>

      {/* Delete Confirm */}
      <ConfirmDialog
        isOpen={!!deleteConfirm}
        onClose={() => setDeleteConfirm(null)}
        onConfirm={() => deleteMutation.mutate(deleteConfirm!.id)}
        title="Delete Exchange Rate"
        message={`Delete rate ${deleteConfirm?.fromCurrency} → ${deleteConfirm?.toCurrency} (${deleteConfirm?.rate})?`}
        confirmText="Delete"
        isDanger
        isLoading={deleteMutation.isPending}
      />
    </div>
  );
}
