// SCB Corridor & FX Policy Page
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { scbAdminApi } from '@/services/api/scbAdminApi';
import { useAuthStore } from '@/stores/authStore';
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 './CorridorPolicyPage.css';

interface Corridor {
  id: string;
  targetSCB: string;
  status: 'active' | 'paused' | 'pending';
  dailyCap: number;
  usedToday: number;
  preferredAsset: string;
  allowedAssets: string[];
}

interface FXPolicy {
  sourceCurrency: string;
  targetCurrency: string;
  spread: number;
  fee: number;
  minAmount: number;
  maxAmount: number;
  status: 'active' | 'paused';
}

export default function CorridorPolicyPage() {
  const { user } = useAuthStore();
  const scbId = user?.sovereignBankId || '';
  const [showCorridorModal, setShowCorridorModal] = useState(false);
  const [showFXModal, setShowFXModal] = useState(false);
  const [selectedCorridor, setSelectedCorridor] = useState<Corridor | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['scb-corridors', scbId],
    queryFn: () => scbAdminApi.getCorridorPolicyDashboard(scbId),
    enabled: !!scbId,
    refetchInterval: 15000,
  });

  const corridors: Corridor[] = data?.corridors || [
    {
      id: 'cor-001',
      targetSCB: 'SCB-002',
      status: 'active',
      dailyCap: 50000000,
      usedToday: 35000000,
      preferredAsset: 'GRU',
      allowedAssets: ['GRU', 'SSU', 'CBDC'],
    },
    {
      id: 'cor-002',
      targetSCB: 'SCB-003',
      status: 'active',
      dailyCap: 30000000,
      usedToday: 12000000,
      preferredAsset: 'SSU',
      allowedAssets: ['SSU', 'CBDC'],
    },
  ];

  const fxPolicies: FXPolicy[] = data?.fxPolicies || [
    {
      sourceCurrency: 'USD',
      targetCurrency: 'EUR',
      spread: 0.001,
      fee: 0.0005,
      minAmount: 1000,
      maxAmount: 10000000,
      status: 'active',
    },
    {
      sourceCurrency: 'USD',
      targetCurrency: 'GBP',
      spread: 0.0015,
      fee: 0.0008,
      minAmount: 1000,
      maxAmount: 5000000,
      status: 'active',
    },
  ];

  const corridorColumns: Column<Corridor>[] = [
    { key: 'targetSCB', header: 'Target SCB', sortable: true },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'dailyCap',
      header: 'Daily Cap',
      render: (row) => `$${row.dailyCap.toLocaleString()}`,
    },
    {
      key: 'usedToday',
      header: 'Used Today',
      render: (row) => `$${row.usedToday.toLocaleString()}`,
    },
    {
      key: 'utilization',
      header: 'Utilization',
      render: (row) => {
        const percent = (row.usedToday / row.dailyCap) * 100;
        return `${percent.toFixed(1)}%`;
      },
    },
    { key: 'preferredAsset', header: 'Preferred Asset', sortable: true },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <div className="table-actions">
          <PermissionGate permission={AdminPermission.CORRIDOR_ADJUST_CAPS}>
            <Button
              size="small"
              variant="secondary"
              onClick={() => {
                setSelectedCorridor(row);
                setShowCorridorModal(true);
              }}
            >
              Configure
            </Button>
          </PermissionGate>
          <PermissionGate permission={AdminPermission.CORRIDOR_ENABLE_DISABLE}>
            <Button size="small" variant={row.status === 'active' ? 'danger' : 'primary'}>
              {row.status === 'active' ? 'Pause' : 'Resume'}
            </Button>
          </PermissionGate>
        </div>
      ),
    },
  ];

  const fxColumns: Column<FXPolicy>[] = [
    { key: 'sourceCurrency', header: 'From', sortable: true },
    { key: 'targetCurrency', header: 'To', 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: 'minAmount',
      header: 'Min Amount',
      render: (row) => `$${row.minAmount.toLocaleString()}`,
    },
    {
      key: 'maxAmount',
      header: 'Max Amount',
      render: (row) => `$${row.maxAmount.toLocaleString()}`,
    },
    {
      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.CORRIDOR_REQUEST_CHANGE}>
          <Button size="small" variant="secondary" onClick={() => setShowFXModal(true)}>
            Edit Policy
          </Button>
        </PermissionGate>
      ),
    },
  ];

  const fxRateData = [
    { date: '2024-01-01', USD_EUR: 0.92, USD_GBP: 0.79 },
    { date: '2024-01-02', USD_EUR: 0.93, USD_GBP: 0.80 },
    { date: '2024-01-03', USD_EUR: 0.91, USD_GBP: 0.78 },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>Corridor & FX Policy</h1>
        <PermissionGate permission={AdminPermission.CORRIDOR_REQUEST_CHANGE}>
          <Button variant="primary" onClick={() => setShowCorridorModal(true)}>
            Request Corridor Changes
          </Button>
        </PermissionGate>
      </div>

      <DashboardLayout>
        {/* Corridor Overview */}
        <MetricCard
          title="Active Corridors"
          value={corridors.filter((c) => c.status === 'active').length}
          variant="primary"
        />
        <MetricCard
          title="Total Daily Cap"
          value={`$${corridors.reduce((sum, c) => sum + c.dailyCap, 0).toLocaleString()}`}
          variant="success"
        />
        <MetricCard
          title="Total Used Today"
          value={`$${corridors.reduce((sum, c) => sum + c.usedToday, 0).toLocaleString()}`}
          variant="warning"
        />

        {/* Corridors Table */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>Cross-Border Corridors</h2>
          </div>
          <div className="widget__content">
            <DataTable data={corridors} columns={corridorColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* FX Policies Table */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>FX Policies</h2>
          </div>
          <div className="widget__content">
            <DataTable data={fxPolicies} columns={fxColumns} loading={isLoading} searchable />
          </div>
        </div>

        {/* FX Rate Chart */}
        <div className="widget widget--full-width">
          <div className="widget__header">
            <h2>FX Rate Trends</h2>
          </div>
          <div className="widget__content">
            <LineChart
              data={fxRateData}
              dataKey="date"
              lines={[
                { key: 'USD_EUR', name: 'USD/EUR', color: '#2563eb' },
                { key: 'USD_GBP', name: 'USD/GBP', color: '#10b981' },
              ]}
              height={300}
            />
          </div>
        </div>
      </DashboardLayout>

      {/* Configure Corridor Modal */}
      <Modal
        isOpen={showCorridorModal}
        onClose={() => setShowCorridorModal(false)}
        title={`Configure Corridor - ${selectedCorridor?.targetSCB || 'New'}`}
        size="medium"
      >
        <CorridorForm
          corridor={selectedCorridor}
          onCancel={() => setShowCorridorModal(false)}
          onSubmit={(data) => {
            toast.success('Corridor configured');
            setShowCorridorModal(false);
          }}
        />
      </Modal>

      {/* Edit FX Policy Modal */}
      <Modal
        isOpen={showFXModal}
        onClose={() => setShowFXModal(false)}
        title="Edit FX Policy"
        size="medium"
      >
        <FXPolicyForm
          onCancel={() => setShowFXModal(false)}
          onSubmit={(data) => {
            toast.success('FX policy updated');
            setShowFXModal(false);
          }}
        />
      </Modal>
    </div>
  );
}

function CorridorForm({
  corridor,
  onCancel,
  onSubmit,
}: {
  corridor: Corridor | null;
  onCancel: () => void;
  onSubmit: (data: any) => void;
}) {
  const [formData, setFormData] = useState({
    targetSCB: corridor?.targetSCB || '',
    dailyCap: corridor?.dailyCap.toString() || '',
    preferredAsset: corridor?.preferredAsset || 'GRU',
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <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="Daily Cap"
        type="number"
        value={formData.dailyCap}
        onChange={(e) => setFormData({ ...formData, dailyCap: e.target.value })}
        required
      />
      <FormSelect
        label="Preferred Asset"
        value={formData.preferredAsset}
        onChange={(e) => setFormData({ ...formData, preferredAsset: e.target.value })}
        options={[
          { value: 'GRU', label: 'GRU' },
          { value: 'SSU', label: 'SSU' },
          { value: 'CBDC', label: 'CBDC' },
        ]}
        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">
          {corridor ? 'Update' : 'Create'}
        </Button>
      </div>
    </form>
  );
}

function FXPolicyForm({
  onCancel,
  onSubmit,
}: {
  onCancel: () => void;
  onSubmit: (data: any) => void;
}) {
  const [formData, setFormData] = useState({
    sourceCurrency: 'USD',
    targetCurrency: 'EUR',
    spread: '0.001',
    fee: '0.0005',
    minAmount: '1000',
    maxAmount: '10000000',
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <FormSelect
        label="Source Currency"
        value={formData.sourceCurrency}
        onChange={(e) => setFormData({ ...formData, sourceCurrency: e.target.value })}
        options={[
          { value: 'USD', label: 'USD' },
          { value: 'EUR', label: 'EUR' },
          { value: 'GBP', label: 'GBP' },
        ]}
        required
      />
      <FormSelect
        label="Target Currency"
        value={formData.targetCurrency}
        onChange={(e) => setFormData({ ...formData, targetCurrency: e.target.value })}
        options={[
          { value: 'USD', label: 'USD' },
          { value: 'EUR', label: 'EUR' },
          { value: 'GBP', label: 'GBP' },
        ]}
        required
      />
      <FormInput
        label="Spread (%)"
        type="number"
        step="0.0001"
        value={formData.spread}
        onChange={(e) => setFormData({ ...formData, spread: e.target.value })}
        required
      />
      <FormInput
        label="Fee (%)"
        type="number"
        step="0.0001"
        value={formData.fee}
        onChange={(e) => setFormData({ ...formData, fee: e.target.value })}
        required
      />
      <FormInput
        label="Min Amount"
        type="number"
        value={formData.minAmount}
        onChange={(e) => setFormData({ ...formData, minAmount: e.target.value })}
        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">
          Update Policy
        </Button>
      </div>
    </form>
  );
}
