'use client';

import React, { useState, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import {
  PageContainer,
  PageHeader,
  PageCard,
  PageFilter,
  RefreshButton,
  CreateButton,
} from '@/components/admin/common';
import { Search, Users } from 'lucide-react';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { UserTable } from '@/components/admin/users/UserTable';
import { UserEditDialog } from '@/components/admin/users/UserEditDialog';
import { UserCreateDialog } from '@/components/admin/users/UserCreateDialog';
import {
  listUsers,
  updateUser,
  toggleUserActive,
  deleteUser,
  createUser,
  type User,
} from '@/lib/api/admin/users';

export default function UsersPage() {
  const router = useRouter();
  const queryClient = useQueryClient();

  // Filter and pagination state
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sortBy, setSortBy] = useState('created_at');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');

  // Dialog state
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);

  // Fetch users
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['admin', 'users', { page, pageSize, searchQuery, statusFilter, sortBy, sortOrder }],
    queryFn: () =>
      listUsers({
        page,
        pageSize,
        search: searchQuery || undefined,
        status: statusFilter === 'all' ? undefined : statusFilter,
        sortBy,
        sortOrder,
      }),
  });

  // Mutations
  const updateMutation = useMutation({
    mutationFn: ({ userId, data }: { userId: string; data: Parameters<typeof updateUser>[1] }) =>
      updateUser(userId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
      setIsEditDialogOpen(false);
      setEditingUser(null);
    },
  });

  const toggleActiveMutation = useMutation({
    mutationFn: toggleUserActive,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: deleteUser,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
    },
  });

  const createMutation = useMutation({
    mutationFn: createUser,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'users'] });
      setIsCreateDialogOpen(false);
    },
  });

  // Handlers
  const handleSearch = useCallback((value: string) => {
    setSearchQuery(value);
    setPage(1);
  }, []);

  const handleStatusChange = useCallback((value: 'all' | 'active' | 'inactive') => {
    setStatusFilter(value);
    setPage(1);
  }, []);

  const handleView = useCallback(
    (user: User) => {
      router.push(`/admin/users/${user.id}`);
    },
    [router]
  );

  const handleEdit = useCallback((user: User) => {
    setEditingUser(user);
    setIsEditDialogOpen(true);
  }, []);

  const handleEditSave = useCallback(
    (
      userId: string,
      data: { isActive: boolean; roles: string[]; permissions: string[] }
    ) => {
      updateMutation.mutate({ userId, data });
    },
    [updateMutation]
  );

  const handleToggleActive = useCallback(
    (user: User) => {
      toggleActiveMutation.mutate(user.id);
    },
    [toggleActiveMutation]
  );

  const handleDelete = useCallback(
    (user: User) => {
      deleteMutation.mutate(user.id);
    },
    [deleteMutation]
  );

  const handleSortChange = useCallback((newSortBy: string, newSortOrder: 'asc' | 'desc') => {
    setSortBy(newSortBy);
    setSortOrder(newSortOrder);
  }, []);

  const handleCreate = useCallback((data: Parameters<typeof createUser>[0]) => {
    createMutation.mutate(data);
  }, [createMutation]);

  const users = data?.items || [];
  const total = data?.total || 0;

  return (
    <PageContainer>
      <PageHeader
        title="用户管理"
        description="管理系统用户、角色和权限"
      />

      <PageCard
        title="用户列表"
        icon={<Users className="h-5 w-5" />}
        headerActions={
          <>
            <CreateButton onClick={() => setIsCreateDialogOpen(true)} label="新建用户" />
            <RefreshButton onClick={() => refetch()} loading={isLoading} />
          </>
        }
      >
        <PageFilter variant="ghost">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索用户名或邮箱..."
              value={searchQuery}
              onChange={(e) => handleSearch(e.target.value)}
              className="pl-9"
            />
          </div>
          <div className="space-y-2">
            <Label>状态筛选</Label>
            <Select value={statusFilter} onValueChange={handleStatusChange}>
              <SelectTrigger className="w-full sm:w-[180px]">
                <SelectValue placeholder="筛选状态" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="active">已启用</SelectItem>
                <SelectItem value="inactive">已禁用</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </PageFilter>

        {/* Error Message */}
        {error && (
          <div className="mb-4 p-4 bg-destructive/10 text-destructive rounded-lg">
            加载用户列表失败: {error.message}
          </div>
        )}

        {/* User Table */}
        <UserTable
          data={users}
          isLoading={isLoading}
          pagination={{
            page,
            pageSize,
            total,
            onPageChange: setPage,
            onPageSizeChange: setPageSize,
          }}
          sorting={{
            sortBy,
            sortOrder,
            onSortChange: handleSortChange,
          }}
          onView={handleView}
          onEdit={handleEdit}
          onToggleActive={handleToggleActive}
          onDelete={handleDelete}
          isToggling={toggleActiveMutation.isPending ? toggleActiveMutation.variables : null}
          isDeleting={deleteMutation.isPending ? deleteMutation.variables : null}
        />
      </PageCard>

      {/* Edit Dialog */}
      <UserEditDialog
        user={editingUser}
        isOpen={isEditDialogOpen}
        onClose={() => {
          setIsEditDialogOpen(false);
          setEditingUser(null);
        }}
        onSave={handleEditSave}
        isSaving={updateMutation.isPending}
      />

      {/* Create Dialog */}
      <UserCreateDialog
        isOpen={isCreateDialogOpen}
        onClose={() => setIsCreateDialogOpen(false)}
        onSave={handleCreate}
        isSaving={createMutation.isPending}
      />
    </PageContainer>
  );
}
