'use client';

import React, { useState } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Edit,
  Trash2,
  Eye,
  Power,
  PowerOff,
  Loader2,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
} from 'lucide-react';
import { type User } from '@/lib/api/admin/users';

interface UserTableProps {
  data: User[];
  isLoading: boolean;
  pagination: {
    page: number;
    pageSize: number;
    total: number;
    onPageChange: (page: number) => void;
    onPageSizeChange: (pageSize: number) => void;
  };
  sorting: {
    sortBy: string;
    sortOrder: 'asc' | 'desc';
    onSortChange: (sortBy: string, sortOrder: 'asc' | 'desc') => void;
  };
  onView: (user: User) => void;
  onEdit: (user: User) => void;
  onToggleActive: (user: User) => void;
  onDelete: (user: User) => void;
  isToggling?: string | null;
  isDeleting?: string | null;
}

interface Column {
  key: string;
  header: string;
  sortable?: boolean;
  cell: (user: User) => React.ReactNode;
}

export function UserTable({
  data,
  isLoading,
  pagination,
  sorting,
  onView,
  onEdit,
  onToggleActive,
  onDelete,
  isToggling,
  isDeleting,
}: UserTableProps) {
  const [deletingUser, setDeletingUser] = useState<User | null>(null);

  const formatDate = (dateStr?: string | number) => {
    if (!dateStr) return '从未';
    const strDate = typeof dateStr === 'number' ? dateStr.toString() : dateStr;
    return new Date(strDate).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const handleSort = (columnKey: string) => {
    if (sorting.sortBy === columnKey) {
      sorting.onSortChange(columnKey, sorting.sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      sorting.onSortChange(columnKey, 'asc');
    }
  };

  const SortIcon = ({ columnKey }: { columnKey: string }) => {
    if (sorting.sortBy !== columnKey) {
      return <ArrowUpDown className="w-3 h-3 ml-1 opacity-50" />;
    }
    return sorting.sortOrder === 'asc' ? (
      <ArrowUp className="w-3 h-3 ml-1" />
    ) : (
      <ArrowDown className="w-3 h-3 ml-1" />
    );
  };

  const columns: Column[] = [
    {
      key: 'username',
      header: '用户名',
      sortable: true,
      cell: (user) => <div className="font-medium">{user.username}</div>,
    },
    {
      key: 'email',
      header: '邮箱',
      sortable: true,
      cell: (user) => <div className="text-sm text-muted-foreground">{user.email}</div>,
    },
    {
      key: 'isActive',
      header: '状态',
      sortable: true,
      cell: (user) => (
        <Badge variant={user.isActive ? 'default' : 'secondary'}>
          {user.isActive ? '启用' : '禁用'}
        </Badge>
      ),
    },
    {
      key: 'roles',
      header: '角色',
      cell: (user) => (
        <div className="flex flex-wrap gap-1">
          {user.roles?.slice(0, 2).map((role) => (
            <Badge key={role} variant="outline" className="text-xs">
              {role}
            </Badge>
          ))}
          {user.roles && user.roles.length > 2 && (
            <Badge variant="outline" className="text-xs">
              +{user.roles.length - 2}
            </Badge>
          )}
        </div>
      ),
    },
    {
      key: 'permissions',
      header: '权限',
      cell: (user) => {
        const permissions = user.permissions;
        if (!permissions || permissions.length === 0) return '-';
        return (
          <div className="flex flex-wrap gap-1">
            {permissions.slice(0, 2).map((perm) => (
              <Badge key={perm} variant="outline" className="text-xs">
                {perm}
              </Badge>
            ))}
            {permissions.length > 2 && (
              <Badge variant="outline" className="text-xs">
                +{permissions.length - 2}
              </Badge>
            )}
          </div>
        );
      },
    },
    {
      key: 'createdAt',
      header: '创建时间',
      sortable: true,
      cell: (user) => (
        <div className="text-sm text-muted-foreground">{formatDate(user.createdAt)}</div>
      ),
    },
    {
      key: 'lastLogin',
      header: '最后登录',
      sortable: true,
      cell: (user) => (
        <div className="text-sm text-muted-foreground">{formatDate(user.lastLogin)}</div>
      ),
    },
  ];

  const totalPages = Math.ceil(pagination.total / pagination.pageSize);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              {columns.map((column) => (
                <TableHead key={column.key}>
                  {column.sortable ? (
                    <button
                      className="flex items-center hover:text-foreground transition-colors"
                      onClick={() => handleSort(column.key)}
                    >
                      {column.header}
                      <SortIcon columnKey={column.key} />
                    </button>
                  ) : (
                    column.header
                  )}
                </TableHead>
              ))}
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {data.length === 0 ? (
              <TableRow>
                <TableCell colSpan={columns.length + 1} className="h-24 text-center">
                  暂无数据
                </TableCell>
              </TableRow>
            ) : (
              data.map((user) => (
                <TableRow key={user.id}>
                  {columns.map((column) => (
                    <TableCell key={column.key}>{column.cell(user)}</TableCell>
                  ))}
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onView(user)}
                        title="查看详情"
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onEdit(user)}
                        title="编辑"
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => onToggleActive(user)}
                        disabled={isToggling === user.id}
                        title={user.isActive ? '禁用' : '启用'}
                      >
                        {isToggling === user.id ? (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        ) : user.isActive ? (
                          <PowerOff className="h-4 w-4 text-destructive" />
                        ) : (
                          <Power className="h-4 w-4 text-green-500" />
                        )}
                      </Button>
                      <AlertDialog
                        open={deletingUser?.id === user.id}
                        onOpenChange={(open) => !open && setDeletingUser(null)}
                      >
                        <AlertDialogTrigger asChild>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-destructive hover:text-destructive"
                            onClick={() => setDeletingUser(user)}
                            disabled={isDeleting === user.id}
                            title="删除"
                          >
                            {isDeleting === user.id ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <Trash2 className="h-4 w-4" />
                            )}
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>确认删除用户</AlertDialogTitle>
                            <AlertDialogDescription>
                              您确定要删除用户 &quot;{user.username}&quot; 吗？
                              此操作不可撤销，用户的数据将被永久删除。
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel onClick={() => setDeletingUser(null)}>
                              取消
                            </AlertDialogCancel>
                            <AlertDialogAction
                              onClick={() => {
                                onDelete(user);
                                setDeletingUser(null);
                              }}
                              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                            >
                              删除
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <span>
            第 {pagination.page} 页，共 {totalPages || 1} 页
          </span>
          <span className="hidden sm:inline">({pagination.total} 条记录)</span>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="icon"
            onClick={() => pagination.onPageChange(1)}
            disabled={pagination.page === 1}
          >
            <ChevronsLeft className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            size="icon"
            onClick={() => pagination.onPageChange(pagination.page - 1)}
            disabled={pagination.page === 1}
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            size="icon"
            onClick={() => pagination.onPageChange(pagination.page + 1)}
            disabled={pagination.page >= totalPages}
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
          <Button
            variant="outline"
            size="icon"
            onClick={() => pagination.onPageChange(totalPages)}
            disabled={pagination.page >= totalPages}
          >
            <ChevronsRight className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );
}
