'use client';

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

interface CurrencyRate {
  id: string;
  code: string;
  name: string;
  symbol: string;
  baseCurrencyCode: string;
  exchangeRate: number;
  isActive: boolean;
  createdAt: string;
}

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

export default function CurrenciesPage() {
  const [editingRate, setEditingRate] = useState<CurrencyRate | null>(null);
  const [rateInput, setRateInput] = useState('');
  const [error, setError] = useState<string | null>(null);
  const queryClient = useQueryClient();

  const { data: currencies = [], isLoading } = useQuery<CurrencyRate[]>({
    queryKey: ['currencies'],
    queryFn: () => apiClient.get('/currencies'),
  });

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

  const syncMutation = useMutation({
    mutationFn: () => apiClient.post('/currencies/sync-rates', {}),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['currencies'] }),
    onError: (err: any) => setError(err.response?.data?.message || 'Failed to sync rates'),
  });

  const handleEdit = (currency: CurrencyRate) => {
    setEditingRate(currency);
    setRateInput(currency.exchangeRate.toString());
    setError(null);
  };

  const handleSave = async () => {
    const rate = parseFloat(rateInput);
    if (isNaN(rate) || rate <= 0) {
      setError('Exchange rate must be a positive number');
      return;
    }
    await updateMutation.mutateAsync({ id: editingRate!.id, exchangeRate: rate });
  };

  const currenciesArray = Array.isArray(currencies) ? currencies : (currencies as any)?.items ?? [];

  const columns = [
    {
      key: 'code',
      label: 'Currency',
      render: (c: CurrencyRate) => (
        <div className="flex items-center gap-3">
          <span className="text-2xl font-bold text-muted-foreground w-10 text-center">
            {CURRENCY_META[c.code]?.symbol ?? c.symbol}
          </span>
          <div>
            <div className="font-semibold">{c.code}</div>
            <div className="text-xs text-muted-foreground">{CURRENCY_META[c.code]?.name ?? c.name}</div>
          </div>
        </div>
      ),
    },
    {
      key: 'baseCurrencyCode',
      label: 'Base',
      render: (c: CurrencyRate) => (
        <span className="font-mono text-sm text-muted-foreground">{c.baseCurrencyCode}</span>
      ),
    },
    {
      key: 'exchangeRate',
      label: 'Exchange Rate',
      render: (c: CurrencyRate) => (
        <div>
          <div className="font-mono font-semibold">
            1 {c.baseCurrencyCode} = {c.exchangeRate} {c.code}
          </div>
          <div className="text-xs text-muted-foreground">
            1 {c.code} = {(1 / c.exchangeRate).toFixed(6)} {c.baseCurrencyCode}
          </div>
        </div>
      ),
    },
    {
      key: 'createdAt',
      label: 'Last Updated',
      render: (c: CurrencyRate) => (
        <span className="text-sm text-muted-foreground">
          {new Date(c.createdAt).toLocaleDateString()}
        </span>
      ),
    },
  ];

  const actions = [
    {
      label: 'Edit Rate',
      onClick: handleEdit,
      variant: 'secondary' as const,
      icon: Edit,
    },
  ];

  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 ETB exchange rates for display currencies (DJF, USD)
          </p>
        </div>
        <ActionButton
          icon={RefreshCw}
          variant="secondary"
          onClick={() => syncMutation.mutate()}
          loading={syncMutation.isPending}
        >
          Sync Rates
        </ActionButton>
      </div>

      {error && !editingRate && (
        <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">
        <div className="grid grid-cols-3 gap-4 mb-6">
          {(['ETB', 'DJF', 'USD'] as const).map((code) => {
            const entry = currenciesArray.find((c: CurrencyRate) => c.code === code);
            return (
              <div
                key={code}
                className="p-4 rounded-lg border bg-muted/30 flex items-center justify-between"
              >
                <div>
                  <div className="text-xs text-muted-foreground font-medium">{CURRENCY_META[code].name}</div>
                  <div className="text-2xl font-bold mt-1">{code}</div>
                </div>
                <div className="text-right">
                  {entry ? (
                    <>
                      <div className="font-mono font-semibold text-lg">{entry.exchangeRate}</div>
                      <div className="text-xs text-muted-foreground">per ETB</div>
                    </>
                  ) : (
                    <span className="text-xs text-muted-foreground">Not configured</span>
                  )}
                </div>
              </div>
            );
          })}
        </div>

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

      <div className="card bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 text-sm text-blue-800 dark:text-blue-300 space-y-1">
        <p className="font-semibold text-blue-900 dark:text-blue-200 mb-2">How it works</p>
        <p>• ETB is the transaction currency — all fares are stored in ETB minor units (1 ETB = 100 minor)</p>
        <p>• DJF and USD rates are used to display prices to passengers in their preferred currency</p>
        <p>• Rates apply globally; changes take effect immediately on the next booking or fare quote</p>
      </div>

      <Modal
        isOpen={!!editingRate}
        onClose={() => { setEditingRate(null); setError(null); }}
        title={`Update Rate — ${editingRate?.code}`}
        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 className="p-3 bg-muted/40 rounded-lg text-sm">
            <span className="text-muted-foreground">Currency: </span>
            <span className="font-semibold">{editingRate?.code} — {CURRENCY_META[editingRate?.code ?? '']?.name}</span>
          </div>

          <div>
            <label className="label">
              1 {editingRate?.baseCurrencyCode} = ? {editingRate?.code}
            </label>
            <input
              type="number"
              min="0.0001"
              step="0.0001"
              value={rateInput}
              onChange={(e) => setRateInput(e.target.value)}
              className="input w-full"
              placeholder="e.g., 3.25"
              autoFocus
            />
            {rateInput && parseFloat(rateInput) > 0 && (
              <p className="text-xs text-muted-foreground mt-1">
                ≈ 1 {editingRate?.code} = {(1 / parseFloat(rateInput)).toFixed(6)} {editingRate?.baseCurrencyCode}
              </p>
            )}
          </div>

          <div className="flex gap-2 justify-end pt-2">
            <ActionButton variant="secondary" onClick={() => { setEditingRate(null); setError(null); }}>
              Cancel
            </ActionButton>
            <ActionButton onClick={handleSave} loading={updateMutation.isPending}>
              Save Rate
            </ActionButton>
          </div>
        </div>
      </Modal>
    </div>
  );
}
