// SCB FI Management Page
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { scbAdminApi } from '@/services/api/scbAdminApi';
import { useAuthStore } from '@/stores/authStore';
import Tabs from '@/components/shared/Tabs';
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 PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import { MdBusiness, MdAccountBalance } from 'react-icons/md';
import toast from 'react-hot-toast';
import './FIManagementPage.css';

interface FI {
  id: string;
  name: string;
  bic?: string;
  status: 'approved' | 'pending' | 'suspended';
  apiProfile: string;
  dailyLimit: number;
  usedToday: number;
  lastActivity?: string;
}

interface NostroVostro {
  id: string;
  counterpartySCB: string;
  accountType: 'nostro' | 'vostro';
  balance: number;
  limit: number;
  status: 'active' | 'frozen' | 'closed';
  currency: string;
}

export default function FIManagementPage() {
  const { user } = useAuthStore();
  const scbId = user?.sovereignBankId || '';
  const [showApproveModal, setShowApproveModal] = useState(false);
  const [showLimitModal, setShowLimitModal] = useState(false);
  const [showNostroModal, setShowNostroModal] = useState(false);
  const [selectedFI, setSelectedFI] = useState<FI | null>(null);

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

  const fis: FI[] = data?.fis || [
    {
      id: 'fi-001',
      name: 'Bank Alpha',
      bic: 'ALPHUS33',
      status: 'approved',
      apiProfile: 'Standard',
      dailyLimit: 10000000,
      usedToday: 7500000,
      lastActivity: new Date().toISOString(),
    },
    {
      id: 'fi-002',
      name: 'Bank Beta',
      bic: 'BETAUS33',
      status: 'pending',
      apiProfile: 'Enhanced',
      dailyLimit: 0,
      usedToday: 0,
    },
  ];

  const nostroVostro: NostroVostro[] = data?.nostroVostro || [
    {
      id: 'nv-001',
      counterpartySCB: 'SCB-002',
      accountType: 'nostro',
      balance: 5000000,
      limit: 10000000,
      status: 'active',
      currency: 'USD',
    },
    {
      id: 'nv-002',
      counterpartySCB: 'SCB-003',
      accountType: 'vostro',
      balance: 2000000,
      limit: 5000000,
      status: 'active',
      currency: 'EUR',
    },
  ];

  const fiColumns: Column<FI>[] = [
    { key: 'name', header: 'FI Name', sortable: true },
    { key: 'bic', header: 'BIC', render: (row) => row.bic || '-' },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    { key: 'apiProfile', header: 'API Profile', sortable: true },
    {
      key: 'dailyLimit',
      header: 'Daily Limit',
      render: (row) => `$${row.dailyLimit.toLocaleString()}`,
    },
    {
      key: 'usedToday',
      header: 'Used Today',
      render: (row) => `$${row.usedToday.toLocaleString()}`,
    },
    {
      key: 'utilization',
      header: 'Utilization',
      render: (row) => {
        if (row.dailyLimit === 0) return '-';
        const percent = (row.usedToday / row.dailyLimit) * 100;
        return `${percent.toFixed(1)}%`;
      },
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <div className="table-actions">
          <PermissionGate permission={AdminPermission.FI_APPROVE_SUSPEND}>
            {row.status === 'pending' && (
              <Button
                size="small"
                variant="primary"
                onClick={() => {
                  setSelectedFI(row);
                  setShowApproveModal(true);
                }}
              >
                Approve
              </Button>
            )}
            {row.status === 'approved' && (
              <Button size="small" variant="danger">
                Suspend
              </Button>
            )}
          </PermissionGate>
          <PermissionGate permission={AdminPermission.FI_SET_LIMITS}>
            <Button
              size="small"
              variant="secondary"
              onClick={() => {
                setSelectedFI(row);
                setShowLimitModal(true);
              }}
            >
              Set Limits
            </Button>
          </PermissionGate>
        </div>
      ),
    },
  ];

  const nostroVostroColumns: Column<NostroVostro>[] = [
    { key: 'counterpartySCB', header: 'Counterparty SCB', sortable: true },
    {
      key: 'accountType',
      header: 'Type',
      render: (row) => (
        <span className={`account-type-badge account-type-badge--${row.accountType}`}>
          {row.accountType.toUpperCase()}
        </span>
      ),
    },
    { key: 'currency', header: 'Currency', sortable: true },
    {
      key: 'balance',
      header: 'Balance',
      render: (row) => `${row.currency} ${row.balance.toLocaleString()}`,
    },
    {
      key: 'limit',
      header: 'Limit',
      render: (row) => `${row.currency} ${row.limit.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.NOSTRO_VOSTRO_ADJUST_LIMITS}>
          <Button size="small" variant="secondary">
            Adjust Limits
          </Button>
        </PermissionGate>
      ),
    },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>FI Management & Nostro/Vostro</h1>
        <PermissionGate permission={AdminPermission.NOSTRO_VOSTRO_OPEN}>
          <Button variant="primary" onClick={() => setShowNostroModal(true)}>
            Open New Nostro/Vostro
          </Button>
        </PermissionGate>
      </div>

      <Tabs
        tabs={[
          { id: 'fis', label: 'Financial Institutions', icon: <MdBusiness /> },
          { id: 'nostro-vostro', label: 'Nostro/Vostro Accounts', icon: <MdAccountBalance /> },
        ]}
      >
        {(activeTab) => {
          if (activeTab === 'fis') {
            return (
              <DashboardLayout>
                <MetricCard
                  title="Total FIs"
                  value={fis.length}
                  variant="primary"
                />
                <MetricCard
                  title="Approved FIs"
                  value={fis.filter((f) => f.status === 'approved').length}
                  variant="success"
                />
                <MetricCard
                  title="Pending Approvals"
                  value={fis.filter((f) => f.status === 'pending').length}
                  variant="warning"
                />
                <div className="widget widget--full-width">
                  <div className="widget__header">
                    <h2>Financial Institutions Directory</h2>
                  </div>
                  <div className="widget__content">
                    <DataTable data={fis} columns={fiColumns} loading={isLoading} searchable />
                  </div>
                </div>
              </DashboardLayout>
            );
          }

          if (activeTab === 'nostro-vostro') {
            return (
              <DashboardLayout>
                <MetricCard
                  title="Total Accounts"
                  value={nostroVostro.length}
                  variant="primary"
                />
                <MetricCard
                  title="Total Balance"
                  value={`$${nostroVostro.reduce((sum, nv) => sum + nv.balance, 0).toLocaleString()}`}
                  variant="success"
                />
                <MetricCard
                  title="Active Accounts"
                  value={nostroVostro.filter((nv) => nv.status === 'active').length}
                  variant="info"
                />
                <div className="widget widget--full-width">
                  <div className="widget__header">
                    <h2>Nostro/Vostro Accounts</h2>
                  </div>
                  <div className="widget__content">
                    <DataTable
                      data={nostroVostro}
                      columns={nostroVostroColumns}
                      loading={isLoading}
                      searchable
                    />
                  </div>
                </div>
              </DashboardLayout>
            );
          }

          return null;
        }}
      </Tabs>

      {/* Approve FI Modal */}
      <Modal
        isOpen={showApproveModal}
        onClose={() => setShowApproveModal(false)}
        title="Approve Financial Institution"
        size="small"
      >
        {selectedFI && (
          <div>
            <p>Approve {selectedFI.name} for participation?</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('FI approved');
                  setShowApproveModal(false);
                }}
              >
                Approve
              </Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Set Limits Modal */}
      <Modal
        isOpen={showLimitModal}
        onClose={() => setShowLimitModal(false)}
        title={`Set Daily Limits - ${selectedFI?.name}`}
        size="medium"
      >
        <LimitForm
          fi={selectedFI}
          onCancel={() => setShowLimitModal(false)}
          onSubmit={(data) => {
            toast.success('Daily limits updated');
            setShowLimitModal(false);
          }}
        />
      </Modal>

      {/* Open Nostro/Vostro Modal */}
      <Modal
        isOpen={showNostroModal}
        onClose={() => setShowNostroModal(false)}
        title="Open New Nostro/Vostro Account"
        size="medium"
      >
        <NostroVostroForm
          onCancel={() => setShowNostroModal(false)}
          onSubmit={(data) => {
            toast.success('Nostro/Vostro account opened');
            setShowNostroModal(false);
          }}
        />
      </Modal>
    </div>
  );
}

function LimitForm({
  fi,
  onCancel,
  onSubmit,
}: {
  fi: FI | null;
  onCancel: () => void;
  onSubmit: (data: any) => void;
}) {
  const [formData, setFormData] = useState({
    dailyLimit: fi?.dailyLimit.toString() || '',
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSubmit({ fiId: fi?.id, dailyLimit: parseFloat(formData.dailyLimit) });
  };

  return (
    <form onSubmit={handleSubmit}>
      <FormInput
        label="Daily Limit"
        type="number"
        value={formData.dailyLimit}
        onChange={(e) => setFormData({ ...formData, dailyLimit: 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
        </Button>
      </div>
    </form>
  );
}

function NostroVostroForm({
  onCancel,
  onSubmit,
}: {
  onCancel: () => void;
  onSubmit: (data: any) => void;
}) {
  const [formData, setFormData] = useState({
    counterpartySCB: '',
    accountType: 'nostro',
    currency: 'USD',
    limit: '',
  });

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

  return (
    <form onSubmit={handleSubmit}>
      <FormSelect
        label="Counterparty SCB"
        value={formData.counterpartySCB}
        onChange={(e) => setFormData({ ...formData, counterpartySCB: e.target.value })}
        options={[
          { value: 'scb-001', label: 'SCB-001' },
          { value: 'scb-002', label: 'SCB-002' },
        ]}
        required
      />
      <FormSelect
        label="Account Type"
        value={formData.accountType}
        onChange={(e) => setFormData({ ...formData, accountType: e.target.value })}
        options={[
          { value: 'nostro', label: 'Nostro' },
          { value: 'vostro', label: 'Vostro' },
        ]}
        required
      />
      <FormSelect
        label="Currency"
        value={formData.currency}
        onChange={(e) => setFormData({ ...formData, currency: e.target.value })}
        options={[
          { value: 'USD', label: 'USD' },
          { value: 'EUR', label: 'EUR' },
          { value: 'GBP', label: 'GBP' },
        ]}
        required
      />
      <FormInput
        label="Initial Limit"
        type="number"
        value={formData.limit}
        onChange={(e) => setFormData({ ...formData, limit: 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">
          Open Account
        </Button>
      </div>
    </form>
  );
}
