'use client';

import { useState } from 'react';
import { useCapabilities, useSetCapability, useCapabilityLogs } from '../hooks/use-users';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { formatDateTime } from '@/lib/utils/date';
import { ChevronLeft, ChevronRight, Shield, Clock } from 'lucide-react';

const CAPABILITY_LABELS: Record<string, string> = {
  LOGIN: '登录',
  TRADING: '交易',
  C2C: 'C2C交易',
  TRANSFER_IN: '划入',
  TRANSFER_OUT: '划出',
  P2P_SEND: 'P2P转出',
  P2P_RECEIVE: 'P2P收款',
  MINING_CLAIM: '挖矿领取',
  KYC: '实名认证',
  PROFILE_EDIT: '编辑资料',
  VIEW_ASSET: '查看资产',
  VIEW_TEAM: '查看团队',
  VIEW_RECORDS: '查看记录',
};

const CAPABILITY_GROUPS = [
  { label: '账户', items: ['LOGIN', 'KYC', 'PROFILE_EDIT'] },
  { label: '交易', items: ['TRADING', 'C2C'] },
  { label: '转账', items: ['TRANSFER_IN', 'TRANSFER_OUT', 'P2P_SEND', 'P2P_RECEIVE'] },
  { label: '挖矿', items: ['MINING_CLAIM'] },
  { label: '查看', items: ['VIEW_ASSET', 'VIEW_TEAM', 'VIEW_RECORDS'] },
];

interface CapabilityManagementProps {
  accountSequence: string;
}

export function CapabilityManagement({ accountSequence }: CapabilityManagementProps) {
  const { data: capabilities, isLoading } = useCapabilities(accountSequence);
  const setCapability = useSetCapability(accountSequence);
  const [logPage, setLogPage] = useState(1);
  const { data: logsData, isLoading: logsLoading } = useCapabilityLogs(accountSequence, { page: logPage, pageSize: 10 });

  // Dialog state
  const [dialogOpen, setDialogOpen] = useState(false);
  const [pendingChange, setPendingChange] = useState<{
    capability: string;
    enabled: boolean;
  } | null>(null);
  const [reason, setReason] = useState('');
  const [expiresAt, setExpiresAt] = useState('');

  const capMap = new Map(
    (capabilities || []).map((c) => [c.capability, c]),
  );

  const handleToggle = (capability: string, currentEnabled: boolean) => {
    const newEnabled = !currentEnabled;
    if (!newEnabled) {
      // Disabling - show dialog for reason
      setPendingChange({ capability, enabled: false });
      setReason('');
      setExpiresAt('');
      setDialogOpen(true);
    } else {
      // Enabling - directly
      setCapability.mutate({ capability, enabled: true, reason: '管理员恢复' });
    }
  };

  const handleConfirmDisable = () => {
    if (!pendingChange) return;
    setCapability.mutate({
      capability: pendingChange.capability,
      enabled: false,
      reason: reason || undefined,
      expiresAt: expiresAt || undefined,
    });
    setDialogOpen(false);
    setPendingChange(null);
  };

  if (isLoading) {
    return (
      <Card>
        <CardContent className="p-6 space-y-4">
          {[...Array(5)].map((_, i) => (
            <Skeleton key={i} className="h-10 w-full" />
          ))}
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* Capability switches */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Shield className="h-5 w-5" />
            功能权限
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-6">
            {CAPABILITY_GROUPS.map((group) => (
              <div key={group.label}>
                <h4 className="text-sm font-medium text-muted-foreground mb-3">{group.label}</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                  {group.items.map((cap) => {
                    const item = capMap.get(cap);
                    const enabled = item?.enabled !== false;
                    return (
                      <div
                        key={cap}
                        className={`flex items-center justify-between p-3 rounded-lg border ${
                          enabled ? 'bg-background' : 'bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800'
                        }`}
                      >
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="text-sm font-medium">{CAPABILITY_LABELS[cap] || cap}</span>
                            {!enabled && (
                              <Badge variant="destructive" className="text-xs">
                                已限制
                              </Badge>
                            )}
                          </div>
                          {!enabled && item?.reason && (
                            <p className="text-xs text-muted-foreground mt-1">原因: {item.reason}</p>
                          )}
                          {!enabled && item?.expiresAt && (
                            <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                              <Clock className="h-3 w-3" />
                              到期: {formatDateTime(item.expiresAt)}
                            </p>
                          )}
                        </div>
                        <Switch
                          checked={enabled}
                          onCheckedChange={() => handleToggle(cap, enabled)}
                          disabled={setCapability.isPending}
                        />
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Change logs */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">变更日志</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>时间</TableHead>
                <TableHead>功能</TableHead>
                <TableHead>操作</TableHead>
                <TableHead>原因</TableHead>
                <TableHead>到期时间</TableHead>
                <TableHead>操作人</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {logsLoading ? (
                [...Array(3)].map((_, i) => (
                  <TableRow key={i}>
                    {[...Array(6)].map((_, j) => (
                      <TableCell key={j}><Skeleton className="h-4 w-full" /></TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (logsData?.data || []).length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                    暂无变更记录
                  </TableCell>
                </TableRow>
              ) : (
                (logsData?.data || []).map((log) => (
                  <TableRow key={log.id}>
                    <TableCell className="text-sm">{formatDateTime(log.createdAt)}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{CAPABILITY_LABELS[log.capability] || log.capability}</Badge>
                    </TableCell>
                    <TableCell>
                      {log.action === 'DISABLE' ? (
                        <Badge variant="destructive">禁用</Badge>
                      ) : log.action === 'ENABLE' ? (
                        <Badge className="bg-green-500">启用</Badge>
                      ) : (
                        <Badge variant="secondary">{log.action}</Badge>
                      )}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate">
                      {log.reason || '-'}
                    </TableCell>
                    <TableCell className="text-sm">
                      {log.expiresAt ? formatDateTime(log.expiresAt) : '-'}
                    </TableCell>
                    <TableCell className="text-sm font-mono">{log.operatorId || '-'}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {/* Pagination */}
          {(logsData?.total || 0) > 10 && (
            <div className="flex items-center justify-between p-4 border-t">
              <p className="text-sm text-muted-foreground">
                共 {logsData?.total} 条，第 {logPage} / {Math.ceil((logsData?.total || 0) / 10)} 页
              </p>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setLogPage(logPage - 1)}
                  disabled={logPage <= 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setLogPage(logPage + 1)}
                  disabled={logPage >= Math.ceil((logsData?.total || 0) / 10)}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Disable confirmation dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              确认禁用「{pendingChange ? CAPABILITY_LABELS[pendingChange.capability] || pendingChange.capability : ''}」
            </DialogTitle>
            <DialogDescription>
              禁用后用户将无法使用该功能，请填写原因。
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="reason">禁用原因</Label>
              <Input
                id="reason"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                placeholder="请输入禁用原因（必填）"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="expiresAt">到期时间（可选，留空为永久禁用）</Label>
              <Input
                id="expiresAt"
                type="datetime-local"
                value={expiresAt}
                onChange={(e) => setExpiresAt(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmDisable}
              disabled={!reason.trim() || setCapability.isPending}
            >
              确认禁用
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
