import { useEffect, useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { 
  CheckCircle, 
  Trash2, 
  RefreshCw, 
  Users, 
  Search,
  ChevronLeft,
  ChevronRight,
  Mail,
  AlertCircle,
  XCircle,
} from "lucide-react"
import { Input } from "@/components/ui/input"
import { PendingUser, EmailVerificationSettings } from "../../config"
import { useEmailVerification } from "../../hooks/use-email-verification"

interface PendingUsersTabProps {
  verificationMode: EmailVerificationSettings['verificationMode']
}

export function PendingUsersTab({ verificationMode }: PendingUsersTabProps) {
  const { 
    pendingUsers,
    pendingTotal,
    pendingStats,
    loadingUsers, 
    loadPendingUsers, 
    verifyUser, 
    deleteUser, 
    resendVerification,
    bulkVerify,
    bulkDelete,
    approveUser,
    bulkApprove,
    rejectUser,
    bulkReject,
  } = useEmailVerification()

  const isApprovalMode = verificationMode === 'admin_approval'

  const [selectedUsers, setSelectedUsers] = useState<number[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [currentPage, setCurrentPage] = useState(1)
  const [actionLoading, setActionLoading] = useState<{ [key: string]: boolean }>({})

  const itemsPerPage = 10

  useEffect(() => {
    const request = window.setTimeout(() => loadPendingUsers(currentPage, itemsPerPage, searchQuery), 250)
    return () => window.clearTimeout(request)
  }, [currentPage, searchQuery, loadPendingUsers])

  const totalPages = Math.max(1, Math.ceil(pendingTotal / itemsPerPage))
  const paginatedUsers = pendingUsers

  useEffect(() => {
    if (currentPage > totalPages) setCurrentPage(totalPages)
  }, [currentPage, totalPages])

  const toggleSelectAll = () => {
    if (selectedUsers.length === paginatedUsers.length) {
      setSelectedUsers([])
    } else {
      setSelectedUsers(paginatedUsers.map((u: PendingUser) => u.id))
    }
  }

  const toggleSelectUser = (userId: number) => {
    if (selectedUsers.includes(userId)) {
      setSelectedUsers(selectedUsers.filter(id => id !== userId))
    } else {
      setSelectedUsers([...selectedUsers, userId])
    }
  }

  const handleVerifyUser = async (userId: number) => {
    setActionLoading({ ...actionLoading, [`verify-${userId}`]: true })
    if (isApprovalMode) {
      await approveUser(userId)
    } else {
      await verifyUser(userId)
    }
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setActionLoading({ ...actionLoading, [`verify-${userId}`]: false })
  }

  const handleDeleteUser = async (userId: number) => {
    if (!confirm('Are you sure you want to delete this user?')) return
    setActionLoading({ ...actionLoading, [`delete-${userId}`]: true })
    await deleteUser(userId)
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setActionLoading({ ...actionLoading, [`delete-${userId}`]: false })
  }

  const handleResendVerification = async (userId: number) => {
    setActionLoading({ ...actionLoading, [`resend-${userId}`]: true })
    await resendVerification(userId)
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setActionLoading({ ...actionLoading, [`resend-${userId}`]: false })
  }

  const handleBulkVerify = async () => {
    if (selectedUsers.length === 0) return
    setActionLoading({ ...actionLoading, bulkVerify: true })
    if (isApprovalMode) {
      await bulkApprove(selectedUsers)
    } else {
      await bulkVerify(selectedUsers)
    }
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setSelectedUsers([])
    setActionLoading({ ...actionLoading, bulkVerify: false })
  }

  const handleBulkDelete = async () => {
    if (selectedUsers.length === 0) return
    if (!confirm(`Are you sure you want to delete ${selectedUsers.length} user(s)?`)) return
    setActionLoading({ ...actionLoading, bulkDelete: true })
    await bulkDelete(selectedUsers)
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setSelectedUsers([])
    setActionLoading({ ...actionLoading, bulkDelete: false })
  }

  const handleRejectUser = async (userId: number) => {
    if (!confirm('Are you sure you want to reject this user? They will be notified and their account will be deleted.')) return
    setActionLoading({ ...actionLoading, [`reject-${userId}`]: true })
    await rejectUser(userId)
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setActionLoading({ ...actionLoading, [`reject-${userId}`]: false })
  }

  const handleBulkReject = async () => {
    if (selectedUsers.length === 0) return
    if (!confirm(`Are you sure you want to reject ${selectedUsers.length} user(s)? They will be notified and their accounts will be deleted.`)) return
    setActionLoading({ ...actionLoading, bulkReject: true })
    await bulkReject(selectedUsers)
    await loadPendingUsers(currentPage, itemsPerPage, searchQuery)
    setSelectedUsers([])
    setActionLoading({ ...actionLoading, bulkReject: false })
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const isExpired = (expiryDate: string) => {
    return new Date(expiryDate) < new Date()
  }

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid gap-4 sm:grid-cols-3">
        <Card>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-amber-100">
              <Users className="h-6 w-6 text-amber-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">{pendingStats.pending}</p>
              <p className="text-sm text-muted-foreground">
                {verificationMode === 'admin_approval' ? 'Pending Approval' : 'Pending Verification'}
              </p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-red-100">
              <AlertCircle className="h-6 w-6 text-red-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">
                {pendingStats.expired}
              </p>
              <p className="text-sm text-muted-foreground">Expired Links</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-blue-100">
              <Mail className="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">
                {pendingStats.resends}
              </p>
              <p className="text-sm text-muted-foreground">Emails Resent</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* User Table */}
      <Card>
        <CardHeader>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <CardTitle>Pending Users</CardTitle>
              <CardDescription>
                {verificationMode === 'admin_approval'
                  ? 'Users waiting for admin approval'
                  : 'Users waiting for email verification'
                }
              </CardDescription>
            </div>
            <div className="flex items-center gap-2">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Search users..."
                  className="pl-9 w-[200px]"
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value)
                    setCurrentPage(1)
                  }}
                />
              </div>
              <Button
                variant="outline"
                size="icon"
                onClick={() => loadPendingUsers(currentPage, itemsPerPage, searchQuery)}
                disabled={loadingUsers}
              >
                <RefreshCw className={`h-4 w-4 ${loadingUsers ? 'animate-spin' : ''}`} />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* Bulk Actions - PRO */}
          {selectedUsers.length > 0 && (
            <div className="flex items-center gap-4 mb-4 p-3 bg-muted rounded-lg">
              <span className="text-sm font-medium">
                {selectedUsers.length} user(s) selected
              </span>
              <div className="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={handleBulkVerify}
                  disabled={actionLoading.bulkVerify}
                >
                  <CheckCircle className="h-4 w-4 mr-1" />
                  {verificationMode === 'admin_approval' ? 'Approve All' : 'Verify All'}
                </Button>
                {isApprovalMode && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={handleBulkReject}
                    disabled={actionLoading.bulkReject}
                    className="text-destructive hover:text-destructive"
                  >
                    <XCircle className="h-4 w-4 mr-1" />
                    Reject All
                  </Button>
                )}
                <Button
                  size="sm"
                  variant="outline"
                  onClick={handleBulkDelete}
                  disabled={actionLoading.bulkDelete}
                  className="text-destructive hover:text-destructive"
                >
                  <Trash2 className="h-4 w-4 mr-1" />
                  Delete All
                </Button>
              </div>
            </div>
          )}

          {/* Table */}
          {loadingUsers ? (
            <div className="flex items-center justify-center py-12">
              <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : paginatedUsers.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <Users className="h-12 w-12 text-muted-foreground mb-4" />
              <h3 className="text-lg font-medium">No pending users</h3>
              <p className="text-sm text-muted-foreground">
                {searchQuery 
                  ? "No users match your search criteria" 
                  : verificationMode === 'admin_approval'
                    ? "All users have been reviewed"
                    : "All users have verified their email addresses"}
              </p>
            </div>
          ) : (
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">
                      <Checkbox
                        checked={selectedUsers.length === paginatedUsers.length && paginatedUsers.length > 0}
                        onCheckedChange={toggleSelectAll}
                      />
                    </TableHead>
                    <TableHead>User</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Registered</TableHead>
                    <TableHead>Expires</TableHead>
                    <TableHead>Resent</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {paginatedUsers.map((user: PendingUser) => (
                    <TableRow key={user.id}>
                      <TableCell>
                        <Checkbox
                          checked={selectedUsers.includes(user.id)}
                          onCheckedChange={() => toggleSelectUser(user.id)}
                        />
                      </TableCell>
                      <TableCell>
                        <div>
                          <p className="font-medium">{user.username}</p>
                          <p className="text-sm text-muted-foreground">{user.email}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={user.status === 'verified' ? 'default' : 'secondary'} className={user.status === 'verified' ? 'bg-green-500 hover:bg-green-600' : 'bg-amber-500 hover:bg-amber-600 text-white'}>
                          {user.status === 'verified'
                            ? (verificationMode === 'admin_approval' ? 'Approved' : 'Verified')
                            : (verificationMode === 'admin_approval' ? 'Pending Approval' : 'Pending')
                          }
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">{formatDate(user.registeredAt)}</span>
                      </TableCell>
                      <TableCell>
                        <Badge variant={isExpired(user.expiresAt) ? "destructive" : "secondary"}>
                          {isExpired(user.expiresAt) ? 'Expired' : formatDate(user.expiresAt)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">{user.resendCount}x</span>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          {verificationMode === 'email_verification' && (
                            <Button
                              size="icon"
                              variant="ghost"
                              title="Resend verification email"
                              onClick={() => handleResendVerification(user.id)}
                              disabled={actionLoading[`resend-${user.id}`] || user.status === 'verified'}
                            >
                              <Mail className="h-4 w-4" />
                            </Button>
                          )}
                          <Button
                            size="icon"
                            variant="ghost"
                            title={verificationMode === 'admin_approval' ? 'Approve user' : 'Manually verify user'}
                            onClick={() => handleVerifyUser(user.id)}
                            disabled={actionLoading[`verify-${user.id}`] || user.status === 'verified'}
                          >
                            <CheckCircle className="h-4 w-4" />
                          </Button>
                          {isApprovalMode && (
                            <Button
                              size="icon"
                              variant="ghost"
                              title="Reject user"
                              onClick={() => handleRejectUser(user.id)}
                              disabled={actionLoading[`reject-${user.id}`] || user.status === 'verified'}
                              className="text-destructive hover:text-destructive"
                            >
                              <XCircle className="h-4 w-4" />
                            </Button>
                          )}
                          <Button
                            size="icon"
                            variant="ghost"
                            title="Delete user"
                            onClick={() => handleDeleteUser(user.id)}
                            disabled={actionLoading[`delete-${user.id}`]}
                            className="text-destructive hover:text-destructive"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between mt-4">
              <p className="text-sm text-muted-foreground">
                Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, pendingTotal)} of {pendingTotal} users
              </p>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <span className="text-sm font-medium">
                  Page {currentPage} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
