"use client"

import { useState } from "react"
import { useMutation } from "@tanstack/react-query"
import { toast } from "sonner"
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Mail, Trash2, Ban, SendHorizonal, CheckCircle, XCircle, Copy, Loader2 } from "lucide-react"
import { banUser, deleteUser, sendMagicLink, sendPasswordRecovery, unbanUser } from "@/app/protected/(admin)/dashboard/user-management/action"

// // Mock functions (replace with your actual API calls)
// const updateUser = async (id: string, data: any) => {
//   console.log(`Updating user ${id} with data:`, data)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { id, ...data }
// }

// const deleteUser = async (id: string) => {
//   console.log(`Deleting user ${id}`)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { success: true }
// }

// const sendPasswordRecovery = async (email: string) => {
//   console.log(`Sending password recovery email to ${email}`)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { success: true }
// }

// const sendMagicLink = async (email: string) => {
//   console.log(`Sending magic link to ${email}`)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { success: true }
// }

// const banUser = async (id: string) => {
//   console.log(`Banning user ${id}`)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { success: true }
// }

// const unbanUser = async (id: string) => {
//   console.log(`Unbanning user ${id}`)
//   await new Promise((resolve) => setTimeout(resolve, 500)) // Simulate API call
//   return { success: true }
// }

interface UserDetailsSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  user: any
  onUserUpdate: () => void
}

export function UserDetailsSheet({ open, onOpenChange, user, onUserUpdate }: UserDetailsSheetProps) {
  const [isDeleting, setIsDeleting] = useState(false)

  const deleteUserMutation = useMutation({
    mutationFn: () => deleteUser(user.id),
    onSuccess: () => {
      toast.success("User deleted successfully")
      onUserUpdate()
      onOpenChange(false)
    },
    onError: () => {
      toast.error("Failed to delete user")
    },
    onSettled: () => {
      setIsDeleting(false)
    },
  })

  const sendPasswordRecoveryMutation = useMutation({
    mutationFn: () => {
      if (!user.email) {
        throw new Error("User does not have an email address")
      }
      return sendPasswordRecovery(user.email)
    },
    onSuccess: () => {
      toast.success("Password recovery email sent")
    },
    onError: () => {
      toast.error("Failed to send password recovery email")
    },
  })

  const sendMagicLinkMutation = useMutation({
    mutationFn: () => {
      if (!user.email) {
        throw new Error("User does not have an email address")
      }
      return sendMagicLink(user.email)
    },
    onSuccess: () => {
      toast.success("Magic link sent successfully")
    },
    onError: () => {
      toast.error("Failed to send magic link")
    },
  })

  const toggleBanMutation = useMutation({
    mutationFn: () => {
      if (user.banned_until) {
        return unbanUser(user.id)
      } else {
        return banUser(user.id)
      }
    },
    onSuccess: () => {
      toast.success("User ban status updated")
      onUserUpdate()
    },
    onError: () => {
      toast.error("Failed to update user ban status")
    },
  })

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="sm:max-w-md md:max-w-lg overflow-y-auto">
        <SheetHeader className="space-y-1">
          <SheetTitle className="text-xl flex items-center gap-2">
            {user.email}
            <Button
              variant="ghost"
              size="icon"
              className="h-4 w-4"
              onClick={() => {
                navigator.clipboard.writeText(user.email)
                // Optionally add a toast notification here
              }}
            >
              <Copy className="h-4 w-4" />
            </Button>
            {user.banned_until && <Badge variant="destructive">Banned</Badge>}
            {!user.email_confirmed_at && <Badge variant="outline">Unconfirmed</Badge>}
            {!user.banned_until && user.email_confirmed_at && <Badge variant="default">Active</Badge>}
          </SheetTitle>
        </SheetHeader>

        <div className="mt-6 space-y-8">
          {/* User Information Section */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">User Information</h3>

            <div className="space-y-2 text-sm">
              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">User UID</span>
                <div className="flex items-center">
                  <span className="font-mono">{user.id}</span>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-4 w-4 ml-2"
                    onClick={() => {
                      navigator.clipboard.writeText(user.id)
                      // Optionally add a toast notification here
                    }}
                  >
                    <Copy className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Created at</span>
                <span>{new Date(user.created_at).toLocaleString()}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Updated at</span>
                <span>{new Date(user.updated_at || user.created_at).toLocaleString()}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Invited at</span>
                <span>{user.invited_at ? new Date(user.invited_at).toLocaleString() : "-"}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Confirmation sent at</span>
                <span>{user.confirmation_sent_at ? new Date(user.confirmation_sent_at).toLocaleString() : "-"}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Confirmed at</span>
                <span>{user.email_confirmed_at ? new Date(user.email_confirmed_at).toLocaleString() : "-"}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Last signed in</span>
                <span>{user.last_sign_in_at ? new Date(user.last_sign_in_at).toLocaleString() : "Never"}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">SSO</span>
                <XCircle className="h-4 w-4 text-muted-foreground" />
              </div>
            </div>
          </div>

          <Separator />

          {/* Provider Information Section */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">Provider Information</h3>
            <p className="text-sm text-muted-foreground">The user has the following providers</p>

            <div className="border rounded-md p-4 space-y-3">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Mail className="h-5 w-5" />
                  <div>
                    <div className="font-medium">Email</div>
                    <div className="text-xs text-muted-foreground">Signed in with a email account via OAuth</div>
                  </div>
                </div>
                <Badge variant="outline" className="bg-green-500/10 text-green-500 border-green-500/20">
                  <CheckCircle className="h-3 w-3 mr-1" /> Enabled
                </Badge>
              </div>
            </div>

            <div className="border rounded-md p-4 space-y-4">
              <div className="flex justify-between items-center">
                <div>
                  <h4 className="font-medium">Reset password</h4>
                  <p className="text-xs text-muted-foreground">Send a password recovery email to the user</p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => sendPasswordRecoveryMutation.mutate()}
                  disabled={sendPasswordRecoveryMutation.isPending || !user.email}
                >
                  {sendPasswordRecoveryMutation.isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    <>
                      <Mail className="h-4 w-4 mr-2" />
                      Send password recovery
                    </>
                  )}
                </Button>
              </div>

              <Separator />

              <div className="flex justify-between items-center">
                <div>
                  <h4 className="font-medium">Send magic link</h4>
                  <p className="text-xs text-muted-foreground">Passwordless login via email for the user</p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => sendMagicLinkMutation.mutate()}
                  disabled={sendMagicLinkMutation.isPending || !user.email}
                >
                  {sendMagicLinkMutation.isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    <>
                      <SendHorizonal className="h-4 w-4 mr-2" />
                      Send magic link
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>

          <Separator />

          {/* Danger Zone Section */}
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-destructive">Danger zone</h3>
            <p className="text-sm text-muted-foreground">Be wary of the following features as they cannot be undone.</p>

            <div className="space-y-4">
              <div className="border border-destructive/20 rounded-md p-4 flex justify-between items-center">
                <div>
                  <h4 className="font-medium">Ban user</h4>
                  <p className="text-xs text-muted-foreground">Revoke access to the project for a set duration</p>
                </div>
                <Button
                  variant={user.banned_until ? "outline" : "outline"}
                  size="sm"
                  onClick={() => toggleBanMutation.mutate()}
                  disabled={toggleBanMutation.isPending}
                >
                  {toggleBanMutation.isPending ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      {user.banned_until ? "Unbanning..." : "Banning..."}
                    </>
                  ) : (
                    <>
                      <Ban className="h-4 w-4 mr-2" />
                      {user.banned_until ? "Unban user" : "Ban user"}
                    </>
                  )}
                </Button>
              </div>

              <div className="border border-destructive/20 rounded-md p-4 flex justify-between items-center">
                <div>
                  <h4 className="font-medium">Delete user</h4>
                  <p className="text-xs text-muted-foreground">User will no longer have access to the project</p>
                </div>
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="destructive" size="sm">
                      <Trash2 className="h-4 w-4 mr-2" />
                      Delete user
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                      <AlertDialogDescription>
                        This action cannot be undone. This will permanently delete the user account and remove their
                        data from our servers.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Cancel</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => {
                          setIsDeleting(true)
                          deleteUserMutation.mutate()
                        }}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        {isDeleting ? (
                          <>
                            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                            Deleting...
                          </>
                        ) : (
                          "Delete"
                        )}
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </div>
          </div>
        </div>

        <SheetFooter className="mt-6">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Close
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}

