'use client'

import { useState } from 'react'
import { useSession } from 'next-auth/react'
import { StaffRole, StaffStatus } from '@prisma/client'
import {
  useStaffList,
  useInvitations,
  useUpdateStaff,
  useDeleteStaff,
  useCancelInvitation,
} from '@/hooks/use-staff'
import { hasPermission } from '@/lib/services/permission-service'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  MoreHorizontal,
  Search,
  UserPlus,
  Shield,
  ShieldCheck,
  ShieldAlert,
  Clock,
  Trash2,
  UserX,
  UserCheck,
} from 'lucide-react'
import { InviteStaffDialog } from '@/components/admin/invite-staff-dialog'

const roleColors: Record<StaffRole, string> = {
  OWNER: 'bg-purple-100 text-purple-800',
  ADMIN: 'bg-blue-100 text-blue-800',
  MANAGER: 'bg-green-100 text-green-800',
  SUPPORT: 'bg-gray-100 text-gray-800',
}

const roleIcons: Record<StaffRole, typeof Shield> = {
  OWNER: ShieldAlert,
  ADMIN: ShieldCheck,
  MANAGER: Shield,
  SUPPORT: Shield,
}

const statusColors: Record<StaffStatus, string> = {
  ACTIVE: 'bg-green-100 text-green-800',
  SUSPENDED: 'bg-red-100 text-red-800',
}

export default function StaffPage() {
  const { data: session } = useSession()
  const userRole = (session?.user?.role as StaffRole) || 'SUPPORT'

  const [search, setSearch] = useState('')
  const [showInviteDialog, setShowInviteDialog] = useState(false)
  const [staffToDelete, setStaffToDelete] = useState<string | null>(null)
  const [inviteToCancel, setInviteToCancel] = useState<string | null>(null)

  const { data: staffData, isLoading: staffLoading } = useStaffList({ search })
  const { data: invitesData, isLoading: invitesLoading } = useInvitations()
  const updateStaff = useUpdateStaff()
  const deleteStaff = useDeleteStaff()
  const cancelInvitation = useCancelInvitation()

  const canManage = hasPermission(userRole, 'staff:manage')
  const canInvite = hasPermission(userRole, 'staff:invite')
  const canDelete = hasPermission(userRole, 'staff:delete')

  const handleStatusChange = async (id: string, status: StaffStatus) => {
    try {
      await updateStaff.mutateAsync({ id, data: { status } })
    } catch {
      // Error handled by mutation
    }
  }

  const handleRoleChange = async (id: string, role: StaffRole) => {
    try {
      await updateStaff.mutateAsync({ id, data: { role } })
    } catch {
      // Error handled by mutation
    }
  }

  const handleDeleteStaff = async () => {
    if (!staffToDelete) return
    try {
      await deleteStaff.mutateAsync(staffToDelete)
      setStaffToDelete(null)
    } catch {
      // Error handled by mutation
    }
  }

  const handleCancelInvite = async () => {
    if (!inviteToCancel) return
    try {
      await cancelInvitation.mutateAsync(inviteToCancel)
      setInviteToCancel(null)
    } catch {
      // Error handled by mutation
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Staff Management</h1>
          <p className="text-muted-foreground">
            Manage team members and their permissions
          </p>
        </div>
        {canInvite && (
          <Button onClick={() => setShowInviteDialog(true)}>
            <UserPlus className="h-4 w-4 mr-2" />
            Invite Staff
          </Button>
        )}
      </div>

      <Tabs defaultValue="staff">
        <TabsList>
          <TabsTrigger value="staff">
            Staff Members ({staffData?.pagination.total || 0})
          </TabsTrigger>
          <TabsTrigger value="invites">
            Pending Invites ({invitesData?.total || 0})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="staff" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center gap-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    placeholder="Search staff..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {staffLoading ? (
                <div className="text-center py-8 text-muted-foreground">
                  Loading...
                </div>
              ) : !staffData?.staff.length ? (
                <div className="text-center py-8 text-muted-foreground">
                  No staff members found
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Role</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>2FA</TableHead>
                      <TableHead>Joined</TableHead>
                      <TableHead className="w-[50px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {staffData.staff.map((staff) => {
                      const RoleIcon = roleIcons[staff.role]
                      return (
                        <TableRow key={staff.id}>
                          <TableCell className="font-medium">
                            {staff.name || 'No name'}
                            {staff.isCurrentUser && (
                              <Badge variant="outline" className="ml-2">
                                You
                              </Badge>
                            )}
                          </TableCell>
                          <TableCell>{staff.email}</TableCell>
                          <TableCell>
                            {canManage && !staff.isCurrentUser && staff.role !== 'OWNER' ? (
                              <Select
                                value={staff.role}
                                onValueChange={(value) =>
                                  handleRoleChange(staff.id, value as StaffRole)
                                }
                              >
                                <SelectTrigger className="w-[130px]">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="ADMIN">Admin</SelectItem>
                                  <SelectItem value="MANAGER">Manager</SelectItem>
                                  <SelectItem value="SUPPORT">Support</SelectItem>
                                </SelectContent>
                              </Select>
                            ) : (
                              <Badge
                                variant="secondary"
                                className={roleColors[staff.role]}
                              >
                                <RoleIcon className="h-3 w-3 mr-1" />
                                {staff.role}
                              </Badge>
                            )}
                          </TableCell>
                          <TableCell>
                            <Badge
                              variant="secondary"
                              className={statusColors[staff.status]}
                            >
                              {staff.status}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            {staff.twoFactorEnabled ? (
                              <Badge variant="secondary" className="bg-green-100 text-green-800">
                                Enabled
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="bg-gray-100 text-gray-800">
                                Disabled
                              </Badge>
                            )}
                          </TableCell>
                          <TableCell>
                            {new Date(staff.createdAt).toLocaleDateString()}
                          </TableCell>
                          <TableCell>
                            {!staff.isCurrentUser && canManage && (
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button variant="ghost" size="icon">
                                    <MoreHorizontal className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  {staff.status === 'ACTIVE' ? (
                                    <DropdownMenuItem
                                      onClick={() =>
                                        handleStatusChange(staff.id, 'SUSPENDED')
                                      }
                                    >
                                      <UserX className="h-4 w-4 mr-2" />
                                      Suspend
                                    </DropdownMenuItem>
                                  ) : (
                                    <DropdownMenuItem
                                      onClick={() =>
                                        handleStatusChange(staff.id, 'ACTIVE')
                                      }
                                    >
                                      <UserCheck className="h-4 w-4 mr-2" />
                                      Activate
                                    </DropdownMenuItem>
                                  )}
                                  {canDelete && staff.role !== 'OWNER' && (
                                    <>
                                      <DropdownMenuSeparator />
                                      <DropdownMenuItem
                                        className="text-red-600"
                                        onClick={() => setStaffToDelete(staff.id)}
                                      >
                                        <Trash2 className="h-4 w-4 mr-2" />
                                        Delete
                                      </DropdownMenuItem>
                                    </>
                                  )}
                                </DropdownMenuContent>
                              </DropdownMenu>
                            )}
                          </TableCell>
                        </TableRow>
                      )
                    })}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="invites" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Pending Invitations</CardTitle>
              <CardDescription>
                Staff members who have been invited but haven't created their account yet
              </CardDescription>
            </CardHeader>
            <CardContent>
              {invitesLoading ? (
                <div className="text-center py-8 text-muted-foreground">
                  Loading...
                </div>
              ) : !invitesData?.invitations.length ? (
                <div className="text-center py-8 text-muted-foreground">
                  No pending invitations
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Email</TableHead>
                      <TableHead>Role</TableHead>
                      <TableHead>Invited By</TableHead>
                      <TableHead>Expires</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="w-[50px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {invitesData.invitations.map((invite) => (
                      <TableRow key={invite.id}>
                        <TableCell className="font-medium">
                          {invite.email}
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={roleColors[invite.role]}
                          >
                            {invite.role}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {invite.invitedByStaff?.name || invite.invitedByStaff?.email || 'Unknown'}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            <Clock className="h-4 w-4 text-muted-foreground" />
                            {new Date(invite.expiresAt).toLocaleDateString()}
                          </div>
                        </TableCell>
                        <TableCell>
                          {invite.isExpired ? (
                            <Badge variant="destructive">Expired</Badge>
                          ) : (
                            <Badge variant="secondary">Pending</Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          {canInvite && (
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => setInviteToCancel(invite.id)}
                            >
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Invite Dialog */}
      <InviteStaffDialog
        open={showInviteDialog}
        onOpenChange={setShowInviteDialog}
        currentRole={userRole}
      />

      {/* Delete Staff Confirmation */}
      <AlertDialog
        open={!!staffToDelete}
        onOpenChange={() => setStaffToDelete(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Staff Member</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this staff member? This action
              cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeleteStaff}
              className="bg-red-600 hover:bg-red-700"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Cancel Invite Confirmation */}
      <AlertDialog
        open={!!inviteToCancel}
        onOpenChange={() => setInviteToCancel(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Cancel Invitation</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to cancel this invitation? The invite link
              will no longer work.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Keep Invite</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleCancelInvite}
              className="bg-red-600 hover:bg-red-700"
            >
              Cancel Invite
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
