// DBIS CBDC & FX Screen
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { dbisAdminApi } from '@/services/api/dbisAdminApi';
import DashboardLayout from '@/components/layout/DashboardLayout';
import MetricCard from '@/components/shared/MetricCard';
import DataTable, { Column } from '@/components/shared/DataTable';
import Button from '@/components/shared/Button';
import Modal from '@/components/shared/Modal';
import FormInput from '@/components/shared/FormInput';
import FormSelect from '@/components/shared/FormSelect';
import LineChart from '@/components/shared/LineChart';
import PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import toast from 'react-hot-toast';
import './CBDCFXPage.css';

interface CBDCSchema {
  id: string;
  scbId: string;
  type: 'rCBDC' | 'wCBDC' | 'iCBDC';
  status: 'approved' | 'pending' | 'rejected';
  walletSchema: string;
  features: string[];
}

interface FXRoute {
  sourceSCB: string;
  targetSCB: string;
  preferredAsset: string;
  spread: number;
  fee: number;
  status: 'active' | 'paused';
}

export default function CBDCFXPage() {
  const [showApproveModal, setShowApproveModal] = useState(false);
  const [showCorridorModal, setShowCorridorModal] = useState(false);
  const [selectedSchema, setSelectedSchema] = useState<CBDCSchema | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['cbdc-fx'],
    queryFn: () => dbisAdminApi.getCBDCFXDashboard(),
    refetchInterval: 15000,
  });

  const cbdcSchemas: CBDCSchema[] = data?.cbdc?.schemas || [
    {
      id: 'schema-1',
      scbId: 'scb-001',
      type: 'rCBDC',
      status: 'approved',
      walletSchema: 'quantum-safe-v1',
      features: ['offline', 'quantum-safe'],
    },
    {
      id: 'schema-2',
      scbId: 'scb-002',
      type: 'wCBDC',
      status: 'pending',
      walletSchema: 'standard-v2',
      features: ['online-only'],
    },
  ];

  const fxRoutes: FXRoute[] = data?.fx?.routes || [
    { sourceSCB: 'scb-001', targetSCB: 'scb-002', preferredAsset: 'GRU', spread: 0.001, fee: 0.0005, status: 'active' },
    { sourceSCB: 'scb-002', targetSCB: 'scb-003', preferredAsset: 'SSU', spread: 0.002, fee: 0.001, status: 'active' },
  ];

  const cbdcColumns: Column<CBDCSchema>[] = [
    { key: 'scbId', header: 'SCB ID', sortable: true },
    {
      key: 'type',
      header: 'Type',
      render: (row) => <span className="cbdc-type-badge">{row.type}</span>,
    },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    { key: 'walletSchema', header: 'Wallet Schema', sortable: true },
    {
      key: 'features',
      header: 'Features',
      render: (row) => (
        <div className="features-list">
          {row.features.map((f) => (
            <span key={f} className="feature-tag">
              {f}
            </span>
          ))}
        </div>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <PermissionGate permission={AdminPermission.CBDC_APPROVE_TYPE}>
          {row.status === 'pending' && (
            <Button
              size="small"
              variant="primary"
              onClick={() => {
                setSelectedSchema(row);
                setShowApproveModal(true);
              }}
            >
              Approve
            </Button>
          )}
        </PermissionGate>
      ),
    },
  ];

  const fxColumns: Column<FXRoute>[] = [
    { key: 'sourceSCB', header: 'Source SCB', sortable: true },
    { key: 'targetSCB', header: 'Target SCB', sortable: true },
    { key: 'preferredAsset', header: 'Preferred Asset', sortable: true },
    {
      key: 'spread',
      header: 'Spread',
      render: (row) => `${(row.spread * 100).toFixed(3)}%`,
    },
    {
      key: 'fee',
      header: 'Fee',
      render: (row) => `${(row.fee * 100).toFixed(3)}%`,
    },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <PermissionGate permission={AdminPermission.CBDC_CROSS_BORDER_CORRIDOR}>
          <Button size="small" variant="secondary">
            Configure
          </Button>
        </PermissionGate>
      ),
    },
  ];

  const fxPriceData = [
    { date: '2024-01-01', GRU: 1.0, SSU: 0.98, CBDC: 1.01 },
    { date: '2024-01-02', GRU: 1.01, SSU: 0.99, CBDC: 1.02 },
    { date: '2024-01-03', GRU: 1.02, SSU: 1.0, CBDC: 1.01 },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>CBDC & FX</h1>
        <PermissionGate permission={AdminPermission.CBDC_CROSS_BORDER_CORRIDOR}>
          <Button variant="primary" onClick={() => setShowCorridorModal(true)}>
            Set Cross-Border Corridor
          </Button>
        </PermissionGate>
      </div>

      <DashboardLayout>
        {/* CBDC Schemas */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>CBDC Wallet Schemas</h2>
          </div>
          <div className="widget__content">
            <DataTable data={cbdcSchemas} columns={cbdcColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* FX Routing */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>FX/GRU/SSU Routing</h2>
          </div>
          <div className="widget__content">
            <DataTable data={fxRoutes} columns={fxColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* FX Price Chart */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>FX Price Trends</h2>
          </div>
          <div className="widget__content">
            <LineChart
              data={fxPriceData}
              dataKey="date"
              lines={[
                { key: 'GRU', name: 'GRU', color: '#2563eb' },
                { key: 'SSU', name: 'SSU', color: '#10b981' },
                { key: 'CBDC', name: 'CBDC', color: '#f59e0b' },
              ]}
              height={300}
            />
          </div>
        </div>
      </DashboardLayout>

      {/* Approve CBDC Modal */}
      <Modal
        isOpen={showApproveModal}
        onClose={() => setShowApproveModal(false)}
        title="Approve CBDC Type"
        size="medium"
      >
        {selectedSchema && (
          <div>
            <p>Approve {selectedSchema.type} for {selectedSchema.scbId}?</p>
            <div style={{ display: 'flex', gap: '0.75rem', marginTop: '1.5rem', justifyContent: 'flex-end' }}>
              <Button variant="secondary" onClick={() => setShowApproveModal(false)}>
                Cancel
              </Button>
              <Button
                variant="primary"
                onClick={() => {
                  toast.success('CBDC type approved');
                  setShowApproveModal(false);
                }}
              >
                Approve
              </Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Set Corridor Modal */}
      <Modal
        isOpen={showCorridorModal}
        onClose={() => setShowCorridorModal(false)}
        title="Set Cross-Border CBDC Corridor"
        size="medium"
      >
        <CorridorForm onCancel={() => setShowCorridorModal(false)} />
      </Modal>
    </div>
  );
}

function CorridorForm({ onCancel }: { onCancel: () => void }) {
  const [formData, setFormData] = useState({
    sourceSCB: '',
    targetSCB: '',
    allowedAssets: [] as string[],
    maxAmount: '',
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    toast.success('Corridor configured');
    onCancel();
  };

  return (
    <form onSubmit={handleSubmit}>
      <FormSelect
        label="Source SCB"
        value={formData.sourceSCB}
        onChange={(e) => setFormData({ ...formData, sourceSCB: e.target.value })}
        options={[
          { value: 'scb-001', label: 'SCB-001' },
          { value: 'scb-002', label: 'SCB-002' },
        ]}
        required
      />
      <FormSelect
        label="Target SCB"
        value={formData.targetSCB}
        onChange={(e) => setFormData({ ...formData, targetSCB: e.target.value })}
        options={[
          { value: 'scb-001', label: 'SCB-001' },
          { value: 'scb-002', label: 'SCB-002' },
        ]}
        required
      />
      <FormInput
        label="Max Amount"
        type="number"
        value={formData.maxAmount}
        onChange={(e) => setFormData({ ...formData, maxAmount: e.target.value })}
        required
      />
      <div style={{ display: 'flex', gap: '0.75rem', marginTop: '1.5rem', justifyContent: 'flex-end' }}>
        <Button type="button" variant="secondary" onClick={onCancel}>
          Cancel
        </Button>
        <Button type="submit" variant="primary">
          Configure
        </Button>
      </div>
    </form>
  );
}
