'use client';
import { useEffect, useState } from 'react';
import { adminService } from '@/services/admin.service';
import type { DashboardStats } from '@/types/admin.types';

type ActionKey =
  | 'ban' | 'unban' | 'disable' | 'enable' | 'kyc'
  | 'reset' | 'announce' | 'trading' | 'freeze' | 'unfreeze';

type FieldType = 'text' | 'password' | 'textarea' | 'select';

interface FieldDef {
  name: string;
  label: string;
  type: FieldType;
  required?: boolean;
  placeholder?: string;
  defaultValue?: string;
  options?: { value: string; label: string }[];
}

interface ActionDef {
  key: ActionKey;
  label: string;
  description: string;
  variant: 'danger' | 'success' | 'neutral';
  fields: FieldDef[];
  run: (data: Record<string, string>) => Promise<unknown>;
}

const variantButton: Record<ActionDef['variant'], string> = {
  danger: 'bg-red-500/10 text-red-400 border-red-500/20 hover:bg-red-500/20',
  success: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20 hover:bg-emerald-500/20',
  neutral: 'bg-indigo-500/10 text-indigo-400 border-indigo-500/20 hover:bg-indigo-500/20',
};

const quickActions: ActionDef[] = [
  {
    key: 'ban',
    label: 'Ban User',
    description: 'POST /admin/user/ban',
    variant: 'danger',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
      { name: 'reason', label: 'Reason', type: 'text', required: true, placeholder: 'Reason for ban' },
      { name: 'reasonText', label: 'Additional Details', type: 'text', placeholder: 'Optional details' },
    ],
    run: (d) => adminService.banUser({ userId: d.userId, reason: d.reason, reasonText: d.reasonText }),
  },
  {
    key: 'unban',
    label: 'Unban User',
    description: 'POST /admin/user/unban',
    variant: 'success',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
      { name: 'reason', label: 'Reason', type: 'text', placeholder: 'Optional reason' },
    ],
    run: (d) => adminService.unbanUser({ userId: d.userId, reason: d.reason }),
  },
  {
    key: 'disable',
    label: 'Disable User',
    description: 'POST /admin/user/:id/disable',
    variant: 'danger',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
    ],
    run: (d) => adminService.disableUser(d.userId),
  },
  {
    key: 'enable',
    label: 'Enable User',
    description: 'POST /admin/user/:id/enable',
    variant: 'success',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
    ],
    run: (d) => adminService.enableUser(d.userId),
  },
  {
    key: 'kyc',
    label: 'Verify KYC',
    description: 'POST /admin/user/verify-kyc',
    variant: 'success',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
      {
        name: 'approved', label: 'Approved', type: 'select', required: true, defaultValue: 'true',
        options: [
          { value: 'true', label: 'Approved' },
          { value: 'false', label: 'Rejected' },
        ],
      },
      { name: 'notes', label: 'Notes', type: 'textarea', placeholder: 'Optional review notes' },
    ],
    run: (d) => adminService.verifyKyc({ userId: d.userId, approved: d.approved === 'true', notes: d.notes }),
  },
  {
    key: 'reset',
    label: 'Reset Password',
    description: 'POST /admin/user/reset-password',
    variant: 'neutral',
    fields: [
      { name: 'userId', label: 'User ID', type: 'text', required: true, placeholder: 'User ID' },
      { name: 'newPassword', label: 'New Password', type: 'password', required: true, placeholder: 'New password' },
    ],
    run: (d) => adminService.resetPassword({ userId: d.userId, newPassword: d.newPassword }),
  },
  {
    key: 'announce',
    label: 'Create Announcement',
    description: 'POST /admin/announcements',
    variant: 'neutral',
    fields: [
      { name: 'title', label: 'Title', type: 'text', required: true, placeholder: 'Announcement title' },
      { name: 'body', label: 'Body', type: 'textarea', required: true, placeholder: 'Announcement body' },
      {
        name: 'priority', label: 'Priority', type: 'select', required: true, defaultValue: 'INFO',
        options: [
          { value: 'INFO', label: 'Info' },
          { value: 'WARNING', label: 'Warning' },
          { value: 'IMPORTANT', label: 'Important' },
          { value: 'CRITICAL', label: 'Critical' },
        ],
      },
      {
        name: 'target', label: 'Target', type: 'select', required: true, defaultValue: 'ALL',
        options: [
          { value: 'ALL', label: 'All' },
          { value: 'USERS_ONLY', label: 'Users Only' },
          { value: 'ADMINS_ONLY', label: 'Admins Only' },
          { value: 'VERIFIED_USERS', label: 'Verified Users' },
        ],
      },
    ],
    run: (d) => adminService.createAnnouncement({ title: d.title, body: d.body, priority: d.priority, target: d.target }),
  },
  {
    key: 'trading',
    label: 'Toggle Trading',
    description: 'POST /admin/trading/enable|disable',
    variant: 'danger',
    fields: [
      {
        name: 'tradingAction', label: 'Action', type: 'select', required: true, defaultValue: 'enable',
        options: [
          { value: 'enable', label: 'Enable Trading' },
          { value: 'disable', label: 'Disable Trading' },
        ],
      },
      { name: 'reason', label: 'Reason (required when disabling)', type: 'textarea', placeholder: 'Optional unless disabling' },
    ],
    run: (d) =>
      d.tradingAction === 'disable'
        ? adminService.disableTrading(d.reason)
        : adminService.enableTrading(),
  },
  {
    key: 'freeze',
    label: 'Freeze Wallet',
    description: 'POST /admin/wallet/freeze',
    variant: 'danger',
    fields: [
      { name: 'walletId', label: 'Wallet ID', type: 'text', required: true, placeholder: 'Wallet ID' },
      { name: 'reason', label: 'Reason', type: 'text', required: true, placeholder: 'Reason for freeze' },
      { name: 'reasonText', label: 'Additional Details', type: 'text', placeholder: 'Optional details' },
    ],
    run: (d) => adminService.freezeWallet({ walletId: d.walletId, reason: d.reason, reasonText: d.reasonText }),
  },
  {
    key: 'unfreeze',
    label: 'Unfreeze Wallet',
    description: 'POST /admin/wallet/unfreeze',
    variant: 'success',
    fields: [
      { name: 'walletId', label: 'Wallet ID', type: 'text', required: true, placeholder: 'Wallet ID' },
      { name: 'reason', label: 'Reason', type: 'text', placeholder: 'Optional reason' },
    ],
    run: (d) => adminService.unfreezeWallet({ walletId: d.walletId, reason: d.reason }),
  },
];

export default function AdminDashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

  const [activeAction, setActiveAction] = useState<ActionDef | null>(null);
  const [formData, setFormData] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);
  const [feedback, setFeedback] = useState<{ type: 'success' | 'error'; message: string } | null>(null);

  useEffect(() => {
    adminService.getDashboard().then((res) => {
      setStats(res);
      setLoading(false);
    });
  }, []);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setActiveAction(null);
    };
    if (activeAction) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [activeAction]);

  const openAction = (action: ActionDef) => {
    const init: Record<string, string> = {};
    action.fields.forEach((f) => {
      if (f.type === 'select') init[f.name] = f.defaultValue ?? f.options?.[0]?.value ?? '';
    });
    setFormData(init);
    setFeedback(null);
    setActiveAction(action);
  };

  const handleSubmit = async () => {
    if (!activeAction) return;
    const missing = activeAction.fields.filter(
      (f) => f.required && !(formData[f.name] ?? '').trim(),
    );
    if (missing.length) {
      setFeedback({ type: 'error', message: `Missing required field: ${missing.map((m) => m.label).join(', ')}` });
      return;
    }
    setSubmitting(true);
    setFeedback(null);
    try {
      await activeAction.run(formData);
      setFeedback({ type: 'success', message: `${activeAction.label} executed successfully.` });
      setActiveAction(null);
    } catch (e: any) {
      setFeedback({
        type: 'error',
        message: e?.response?.data?.message || e?.message || `${activeAction.label} failed.`,
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return (
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
      {Array.from({ length: 12 }).map((_, i) => (
        <div key={i} className="animate-pulse rounded-xl bg-white/[0.03] p-4 h-24" />
      ))}
    </div>
  );

  if (!stats) return <p className="text-center text-slate-500 py-10">Failed to load dashboard</p>;

  const cards = [
    { label: 'Total Users', value: stats.totalUsers.toLocaleString(), color: 'from-blue-500 to-blue-600' },
    { label: 'Verified Users', value: stats.verifiedUsers.toLocaleString(), color: 'from-emerald-500 to-emerald-600' },
    { label: 'Online Users', value: stats.onlineUsers.toLocaleString(), color: 'from-green-500 to-green-600' },
    { label: 'Today Registrations', value: stats.todayRegistrations.toLocaleString(), color: 'from-cyan-500 to-cyan-600' },
    { label: 'Today Orders', value: stats.todayOrders.toLocaleString(), color: 'from-violet-500 to-violet-600' },
    { label: 'Today Trades', value: stats.todayTrades.toLocaleString(), color: 'from-purple-500 to-purple-600' },
    { label: 'Wallet Volume', value: `$${Number(stats.walletVolume).toLocaleString()}`, color: 'from-indigo-500 to-indigo-600' },
    { label: 'Revenue', value: `$${Number(stats.revenue).toLocaleString()}`, color: 'from-amber-500 to-amber-600' },
    { label: 'Commission', value: `$${Number(stats.commission).toLocaleString()}`, color: 'from-orange-500 to-orange-600' },
    { label: 'Pending Deposits', value: stats.pendingDeposits.toLocaleString(), color: 'from-yellow-500 to-yellow-600' },
    { label: 'Pending Withdrawals', value: stats.pendingWithdrawals.toLocaleString(), color: 'from-rose-500 to-rose-600' },
    { label: 'Open Tickets', value: stats.supportTickets.open.toLocaleString(), color: 'from-pink-500 to-pink-600' },
  ];

  const statusColors: Record<string, string> = { healthy: 'text-emerald-400', degraded: 'text-amber-400', down: 'text-red-400' };

  const inputClass =
    'w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-white placeholder-slate-500 focus:border-indigo-500 focus:outline-none';

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Dashboard</h1>
          <p className="mt-1 text-sm text-white/50">Enterprise FinTech Platform Overview</p>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <span className="text-xs text-slate-400">Server:</span>
            <span className={`text-xs font-medium ${statusColors[stats.serverStatus]}`}>{stats.serverStatus}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs text-slate-400">DB:</span>
            <span className={`text-xs font-medium ${statusColors[stats.databaseStatus]}`}>{stats.databaseStatus}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-xs text-slate-400">API:</span>
            <span className={`text-xs font-medium ${statusColors[stats.apiStatus]}`}>{stats.apiStatus}</span>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {cards.map((card) => (
          <div key={card.label} className="group relative overflow-hidden rounded-xl bg-white/[0.03] border border-white/5 p-4 transition-all hover:bg-white/[0.06]">
            <div className={`absolute inset-0 bg-gradient-to-br ${card.color} opacity-[0.03] group-hover:opacity-[0.06] transition-opacity`} />
            <p className="relative text-xs font-medium text-slate-400 uppercase tracking-wider">{card.label}</p>
            <p className="relative mt-2 text-2xl font-bold text-white">{card.value}</p>
          </div>
        ))}
      </div>

      {/* Support Tickets Summary */}
      <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
        <h3 className="text-sm font-medium text-white mb-3">Support Tickets</h3>
        <div className="grid grid-cols-4 gap-4">
          <div className="text-center">
            <p className="text-2xl font-bold text-white">{stats.supportTickets.open}</p>
            <p className="text-xs text-slate-400">Open</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-amber-400">{stats.supportTickets.inProgress}</p>
            <p className="text-xs text-slate-400">In Progress</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-emerald-400">{stats.supportTickets.resolved}</p>
            <p className="text-xs text-slate-400">Resolved</p>
          </div>
          <div className="text-center">
            <p className="text-2xl font-bold text-slate-400">{stats.supportTickets.closed}</p>
            <p className="text-xs text-slate-400">Closed</p>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
        <div className="mb-4 flex items-center justify-between">
          <div>
            <h3 className="text-sm font-medium text-white">Quick Actions</h3>
            <p className="mt-0.5 text-xs text-slate-500">Trigger backend operations without a dedicated UI</p>
          </div>
        </div>

        {feedback && !activeAction && (
          <div
            className={`mb-4 rounded-lg p-3 text-sm ${
              feedback.type === 'success'
                ? 'bg-emerald-500/10 text-emerald-400'
                : 'bg-red-500/10 text-red-400'
            }`}
          >
            {feedback.message}
          </div>
        )}

        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
          {quickActions.map((action) => (
            <button
              key={action.key}
              onClick={() => openAction(action)}
              className={`flex flex-col items-start gap-1 rounded-lg border px-3 py-3 text-left transition-colors ${variantButton[action.variant]}`}
            >
              <span className="text-sm font-medium">{action.label}</span>
              <span className="text-[10px] font-mono opacity-70">{action.description}</span>
            </button>
          ))}
        </div>
      </div>

      {/* System Status */}
      <div className="grid grid-cols-3 gap-4">
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <p className="text-xs text-slate-400">Server Status</p>
          <p className={`mt-1 text-lg font-bold ${statusColors[stats.serverStatus]}`}>{stats.serverStatus.toUpperCase()}</p>
        </div>
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <p className="text-xs text-slate-400">Database Status</p>
          <p className={`mt-1 text-lg font-bold ${statusColors[stats.databaseStatus]}`}>{stats.databaseStatus.toUpperCase()}</p>
        </div>
        <div className="rounded-xl border border-white/5 bg-white/[0.02] p-4">
          <p className="text-xs text-slate-400">API Status</p>
          <p className={`mt-1 text-lg font-bold ${statusColors[stats.apiStatus]}`}>{stats.apiStatus.toUpperCase()}</p>
        </div>
      </div>

      {/* Action Modal */}
      {activeAction && (
        <div
          className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 p-4 backdrop-blur-sm sm:items-center"
          onClick={() => !submitting && setActiveAction(null)}
        >
          <div
            className="w-full max-w-lg rounded-2xl border border-white/10 bg-[#0c0f17] p-5 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="mb-4 flex items-start justify-between">
              <div>
                <h2 className="text-base font-semibold text-white">{activeAction.label}</h2>
                <p className="mt-0.5 text-xs font-mono text-slate-500">{activeAction.description}</p>
              </div>
              <button
                onClick={() => !submitting && setActiveAction(null)}
                className="rounded-md px-2 py-1 text-slate-400 transition-colors hover:bg-white/5 hover:text-white"
                aria-label="Close"
              >
                ✕
              </button>
            </div>

            {feedback && (
              <div
                className={`mb-4 rounded-lg p-3 text-sm ${
                  feedback.type === 'success'
                    ? 'bg-emerald-500/10 text-emerald-400'
                    : 'bg-red-500/10 text-red-400'
                }`}
              >
                {feedback.message}
              </div>
            )}

            <div className="space-y-3">
              {activeAction.fields.map((field) => (
                <div key={field.name}>
                  <label className="mb-1 block text-xs font-medium text-slate-400">
                    {field.label}
                    {field.required && <span className="ml-0.5 text-red-400">*</span>}
                  </label>
                  {field.type === 'textarea' ? (
                    <textarea
                      rows={3}
                      value={formData[field.name] ?? ''}
                      placeholder={field.placeholder}
                      onChange={(e) => setFormData((p) => ({ ...p, [field.name]: e.target.value }))}
                      className={inputClass}
                    />
                  ) : field.type === 'select' ? (
                    <select
                      value={formData[field.name] ?? ''}
                      onChange={(e) => setFormData((p) => ({ ...p, [field.name]: e.target.value }))}
                      className={inputClass}
                    >
                      {field.options?.map((opt) => (
                        <option key={opt.value} value={opt.value} className="bg-[#0c0f17]">
                          {opt.label}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type={field.type}
                      value={formData[field.name] ?? ''}
                      placeholder={field.placeholder}
                      onChange={(e) => setFormData((p) => ({ ...p, [field.name]: e.target.value }))}
                      className={inputClass}
                    />
                  )}
                </div>
              ))}
            </div>

            <div className="mt-5 flex justify-end gap-2">
              <button
                onClick={() => !submitting && setActiveAction(null)}
                className="rounded-lg border border-white/10 px-4 py-2 text-xs font-medium text-slate-300 hover:bg-white/5"
              >
                Cancel
              </button>
              <button
                onClick={handleSubmit}
                disabled={submitting}
                className={`rounded-lg px-4 py-2 text-xs font-semibold text-white transition-colors disabled:opacity-50 ${
                  activeAction.variant === 'danger'
                    ? 'bg-red-500/80 hover:bg-red-500'
                    : activeAction.variant === 'success'
                    ? 'bg-emerald-500/80 hover:bg-emerald-500'
                    : 'bg-indigo-500/80 hover:bg-indigo-500'
                }`}
              >
                {submitting ? 'Processing…' : 'Submit'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
