// DBIS GRU Command Center Page
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { dbisAdminApi } from '@/services/api/dbisAdminApi';
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 LineChart from '@/components/shared/LineChart';
import PermissionGate from '@/components/auth/PermissionGate';
import { AdminPermission } from '@/constants/permissions';
import { MdAccountBalance, MdTrendingUp, MdSavings, MdPool } from 'react-icons/md';
import toast from 'react-hot-toast';
import './GRUPage.css';

interface GRUClass {
  id: string;
  name: string;
  status: 'active' | 'locked' | 'suspended';
  inCirculation: number;
  price: number;
  volatility: number;
}

interface GRUIndex {
  id: string;
  name: string;
  weight: number;
  components: Array<{ asset: string; weight: number }>;
  price: number;
  change24h: number;
}

interface GRUBond {
  id: string;
  name: string;
  status: 'open' | 'closed';
  totalIssued: number;
  yield: number;
  maturity: string;
}

export default function GRUPage() {
  const [showIssuanceModal, setShowIssuanceModal] = useState(false);
  const [showLockModal, setShowLockModal] = useState(false);
  const [selectedClass, setSelectedClass] = useState<GRUClass | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ['gru-command'],
    queryFn: () => dbisAdminApi.getGRUCommandDashboard(),
    refetchInterval: 15000,
  });

  const gruClasses: GRUClass[] = data?.monetary?.classes || [
    { id: 'm00', name: 'M00', status: 'active', inCirculation: 1000000, price: 1.0, volatility: 0.001 },
    { id: 'm0', name: 'M0', status: 'active', inCirculation: 5000000, price: 1.0, volatility: 0.002 },
    { id: 'm1', name: 'M1', status: 'active', inCirculation: 10000000, price: 1.0, volatility: 0.003 },
  ];

  const gruIndexes: GRUIndex[] = data?.indexes || [
    { id: 'gru-xau', name: 'GRU-XAU', weight: 0.3, components: [{ asset: 'XAU', weight: 1.0 }], price: 1.05, change24h: 0.02 },
    { id: 'gru-basket', name: 'GRU-Basket', weight: 0.7, components: [{ asset: 'Multi', weight: 1.0 }], price: 1.02, change24h: -0.01 },
  ];

  const gruBonds: GRUBond[] = data?.bonds || [
    { id: 'bond-1', name: 'GRU Reserve Bond 2024', status: 'open', totalIssued: 50000000, yield: 0.035, maturity: '2029-12-31' },
  ];

  const handleCreateIssuance = async (formData: any) => {
    try {
      await dbisAdminApi.createGRUIssuanceProposal(formData);
      toast.success('GRU issuance proposal created');
      setShowIssuanceModal(false);
    } catch (error) {
      toast.error('Failed to create issuance proposal');
    }
  };

  const handleLockUnlock = async (classId: string, action: 'lock' | 'unlock') => {
    try {
      await dbisAdminApi.lockUnlockGRUClass({ classId, action });
      toast.success(`GRU class ${action}ed successfully`);
      setShowLockModal(false);
    } catch (error) {
      toast.error(`Failed to ${action} GRU class`);
    }
  };

  const classColumns: Column<GRUClass>[] = [
    { key: 'name', header: 'Class', sortable: true },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'inCirculation',
      header: 'In Circulation',
      render: (row) => `$${row.inCirculation.toLocaleString()}`,
    },
    {
      key: 'price',
      header: 'Price',
      render: (row) => `$${row.price.toFixed(4)}`,
    },
    {
      key: 'volatility',
      header: 'Volatility',
      render: (row) => `${(row.volatility * 100).toFixed(2)}%`,
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (row) => (
        <div className="table-actions">
          <PermissionGate permission={AdminPermission.GRU_LOCK_UNLOCK}>
            <Button
              size="small"
              variant="secondary"
              onClick={() => {
                setSelectedClass(row);
                setShowLockModal(true);
              }}
            >
              {row.status === 'active' ? 'Lock' : 'Unlock'}
            </Button>
          </PermissionGate>
        </div>
      ),
    },
  ];

  const indexColumns: Column<GRUIndex>[] = [
    { key: 'name', header: 'Index Name', sortable: true },
    {
      key: 'price',
      header: 'Price',
      render: (row) => `$${row.price.toFixed(4)}`,
    },
    {
      key: 'change24h',
      header: '24h Change',
      render: (row) => (
        <span className={row.change24h >= 0 ? 'change-positive' : 'change-negative'}>
          {row.change24h >= 0 ? '+' : ''}
          {(row.change24h * 100).toFixed(2)}%
        </span>
      ),
    },
    {
      key: 'weight',
      header: 'Weight',
      render: (row) => `${(row.weight * 100).toFixed(1)}%`,
    },
  ];

  const bondColumns: Column<GRUBond>[] = [
    { key: 'name', header: 'Bond Name', sortable: true },
    {
      key: 'status',
      header: 'Status',
      render: (row) => (
        <span className={`status-badge status-badge--${row.status}`}>{row.status}</span>
      ),
    },
    {
      key: 'totalIssued',
      header: 'Total Issued',
      render: (row) => `$${row.totalIssued.toLocaleString()}`,
    },
    {
      key: 'yield',
      header: 'Yield',
      render: (row) => `${(row.yield * 100).toFixed(2)}%`,
    },
    { key: 'maturity', header: 'Maturity', sortable: true },
  ];

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>GRU Command Center</h1>
        <PermissionGate permission={AdminPermission.GRU_ISSUANCE_PROPOSAL}>
          <Button variant="primary" onClick={() => setShowIssuanceModal(true)}>
            Create Issuance Proposal
          </Button>
        </PermissionGate>
      </div>

      <Tabs
        tabs={[
          { id: 'monetary', label: 'Monetary', icon: <MdAccountBalance /> },
          { id: 'indexes', label: 'Indexes', icon: <MdTrendingUp /> },
          { id: 'bonds', label: 'Bonds', icon: <MdSavings /> },
          { id: 'pools', label: 'Supranational Pools', icon: <MdPool /> },
        ]}
      >
        {(activeTab) => {
          if (activeTab === 'monetary') {
            return (
              <DashboardLayout>
                <MetricCard
                  title="Total GRU in Circulation"
                  value={`$${gruClasses.reduce((sum, c) => sum + c.inCirculation, 0).toLocaleString()}`}
                  variant="primary"
                />
                <MetricCard
                  title="Average Price"
                  value={`$${(
                    gruClasses.reduce((sum, c) => sum + c.price, 0) / gruClasses.length
                  ).toFixed(4)}`}
                  variant="success"
                />
                <MetricCard
                  title="Active Classes"
                  value={gruClasses.filter((c) => c.status === 'active').length}
                  variant="info"
                />
                <div className="widget widget--full-width">
                  <div className="widget__header">
                    <h2>GRU Classes</h2>
                  </div>
                  <div className="widget__content">
                    <DataTable data={gruClasses} columns={classColumns} loading={isLoading} />
                  </div>
                </div>
              </DashboardLayout>
            );
          }

          if (activeTab === 'indexes') {
            return (
              <DashboardLayout>
                <MetricCard
                  title="Total Indexes"
                  value={gruIndexes.length}
                  variant="primary"
                />
                <MetricCard
                  title="Average Price"
                  value={`$${(
                    gruIndexes.reduce((sum, i) => sum + i.price, 0) / gruIndexes.length
                  ).toFixed(4)}`}
                  variant="success"
                />
                <div className="widget widget--full-width">
                  <div className="widget__header">
                    <h2>GRU Indexes</h2>
                  </div>
                  <div className="widget__content">
                    <DataTable data={gruIndexes} columns={indexColumns} loading={isLoading} />
                  </div>
                </div>
              </DashboardLayout>
            );
          }

          if (activeTab === 'bonds') {
            return (
              <DashboardLayout>
                <MetricCard
                  title="Total Bonds"
                  value={gruBonds.length}
                  variant="primary"
                />
                <MetricCard
                  title="Total Issued"
                  value={`$${gruBonds.reduce((sum, b) => sum + b.totalIssued, 0).toLocaleString()}`}
                  variant="success"
                />
                <MetricCard
                  title="Open Issuance Windows"
                  value={gruBonds.filter((b) => b.status === 'open').length}
                  variant="info"
                />
                <div className="widget widget--full-width">
                  <div className="widget__header">
                    <h2>GRU Bonds</h2>
                    <PermissionGate permission={AdminPermission.GRU_BOND_ISSUANCE_WINDOW}>
                      <Button size="small" variant="secondary">
                        Manage Issuance Windows
                      </Button>
                    </PermissionGate>
                  </div>
                  <div className="widget__content">
                    <DataTable data={gruBonds} columns={bondColumns} loading={isLoading} />
                  </div>
                </div>
              </DashboardLayout>
            );
          }

          if (activeTab === 'pools') {
            return (
              <DashboardLayout>
                <MetricCard title="Supranational Pools" value="Coming Soon" variant="primary" />
              </DashboardLayout>
            );
          }

          return null;
        }}
      </Tabs>

      {/* Issuance Proposal Modal */}
      <Modal
        isOpen={showIssuanceModal}
        onClose={() => setShowIssuanceModal(false)}
        title="Create GRU Issuance Proposal"
        size="medium"
      >
        <GRUIssuanceForm onSubmit={handleCreateIssuance} onCancel={() => setShowIssuanceModal(false)} />
      </Modal>

      {/* Lock/Unlock Modal */}
      <Modal
        isOpen={showLockModal}
        onClose={() => setShowLockModal(false)}
        title={`${selectedClass?.status === 'active' ? 'Lock' : 'Unlock'} GRU Class`}
        size="small"
      >
        {selectedClass && (
          <div>
            <p>Are you sure you want to {selectedClass.status === 'active' ? 'lock' : 'unlock'} {selectedClass.name}?</p>
            <div style={{ display: 'flex', gap: '0.75rem', marginTop: '1.5rem', justifyContent: 'flex-end' }}>
              <Button variant="secondary" onClick={() => setShowLockModal(false)}>
                Cancel
              </Button>
              <Button
                variant={selectedClass.status === 'active' ? 'danger' : 'primary'}
                onClick={() => handleLockUnlock(selectedClass.id, selectedClass.status === 'active' ? 'lock' : 'unlock')}
              >
                {selectedClass.status === 'active' ? 'Lock' : 'Unlock'}
              </Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

// GRU Issuance Form Component
function GRUIssuanceForm({ onSubmit, onCancel }: { onSubmit: (data: any) => void; onCancel: () => void }) {
  const [formData, setFormData] = useState({
    classId: '',
    amount: '',
    reason: '',
    targetDate: '',
  });

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

  return (
    <form onSubmit={handleSubmit}>
      <FormSelect
        label="GRU Class"
        value={formData.classId}
        onChange={(e) => setFormData({ ...formData, classId: e.target.value })}
        options={[
          { value: 'm00', label: 'M00' },
          { value: 'm0', label: 'M0' },
          { value: 'm1', label: 'M1' },
        ]}
        required
      />
      <FormInput
        label="Amount"
        type="number"
        value={formData.amount}
        onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
        required
      />
      <FormInput
        label="Target Date"
        type="date"
        value={formData.targetDate}
        onChange={(e) => setFormData({ ...formData, targetDate: e.target.value })}
        required
      />
      <FormInput
        label="Reason"
        value={formData.reason}
        onChange={(e) => setFormData({ ...formData, reason: 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">
          Create Proposal
        </Button>
      </div>
    </form>
  );
}
