"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import {
  Sheet,
  SheetContent,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/app/_components/ui/sheet";
import { Button } from "@/app/_components/ui/button";
import { Badge } from "@/app/_components/ui/badge";
import { Separator } from "@/app/_components/ui/separator";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/app/_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";
import { format } from "date-fns";

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 [isLoading, setIsLoading] = useState({
    deleteUser: false,
    sendPasswordRecovery: false,
    sendMagicLink: false,
    toggleBan: false,
  });

  const handleDeleteUser = async () => {
    setIsLoading((prev) => ({ ...prev, deleteUser: true }));
    setIsDeleting(true);
    try {
      await deleteUser(user.id);
      toast.success("User deleted successfully");
      onUserUpdate();
      onOpenChange(false);
    } catch {
      toast.error("Failed to delete user");
    } finally {
      setIsLoading((prev) => ({ ...prev, deleteUser: false }));
      setIsDeleting(false);
    }
  };

  const handleSendPasswordRecovery = async () => {
    setIsLoading((prev) => ({ ...prev, sendPasswordRecovery: true }));
    try {
      if (!user.email) {
        throw new Error("User does not have an email address");
      }
      await sendPasswordRecovery(user.email);
      toast.success("Password recovery email sent");
    } catch {
      toast.error("Failed to send password recovery email");
    } finally {
      setIsLoading((prev) => ({ ...prev, sendPasswordRecovery: false }));
    }
  };

  const handleSendMagicLink = async () => {
    setIsLoading((prev) => ({ ...prev, sendMagicLink: true }));
    try {
      if (!user.email) {
        throw new Error("User does not have an email address");
      }
      await sendMagicLink(user.email);
      toast.success("Magic link sent successfully");
    } catch {
      toast.error("Failed to send magic link");
    } finally {
      setIsLoading((prev) => ({ ...prev, sendMagicLink: false }));
    }
  };

  const handleToggleBan = async () => {
    setIsLoading((prev) => ({ ...prev, toggleBan: true }));
    try {
      if (user.banned_until) {
        await unbanUser(user.id);
      } else {
        await banUser(user.id);
      }
      toast.success("User ban status updated");
      onUserUpdate();
    } catch {
      toast.error("Failed to update user ban status");
    } finally {
      setIsLoading((prev) => ({ ...prev, toggleBan: false }));
    }
  };

  const handleCopyItem = (item: string) => {
    navigator.clipboard.writeText(item);
    toast.success("Copied to clipboard");
  };

  const formatDate = (date: string | undefined | null) => {
    return date ? format(new Date(date), "PPpp") : "-";
  };

  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={() => handleCopyItem(user.email)}
            >
              <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={() => handleCopyItem(user.id)}
                  >
                    <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>{formatDate(user.invited_at)}</span>
              </div>

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">
                  Confirmation sent at
                </span>
                <span>{formatDate(user.email_confirmation_sent_at)}</span>
              </div>

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

              <div className="flex justify-between items-center py-1">
                <span className="text-muted-foreground">Last signed in</span>
                <span>{formatDate(user.last_sign_in_at)}</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={handleSendPasswordRecovery}
                  disabled={isLoading.sendPasswordRecovery || !user.email}
                >
                  {isLoading.sendPasswordRecovery ? (
                    <>
                      <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={handleSendMagicLink}
                  disabled={isLoading.sendMagicLink || !user.email}
                >
                  {isLoading.sendMagicLink ? (
                    <>
                      <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={handleToggleBan}
                  disabled={isLoading.toggleBan}
                >
                  {isLoading.toggleBan ? (
                    <>
                      <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"
                      disabled={isDeleting}
                    >
                      {isDeleting ? (
                        <>
                          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                          Deleting...
                        </>
                      ) : (
                        <>
                          <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={handleDeleteUser}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                        disabled={isDeleting}
                      >
                        {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>
  );
}
