"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { MoreHorizontal, Edit, Trash, Loader2, Eye, EyeOff } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { updateUser, deleteUser } from "./actions";
import type { Branch, Role } from "@/lib/types";

export function UserRowActions({
  user,
  roles,
  branches,
}: {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  user: any;
  roles: Role[];
  branches: Branch[];
}) {
  const [openSheet, setOpenSheet] = useState(false);
  const [openDelete, setOpenDelete] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [pending, startTransition] = useTransition();

  function onUpdate(formData: FormData) {
    startTransition(async () => {
      const res = await updateUser(undefined, formData);
      if (res?.ok) {
        toast.success("User updated");
        setOpenSheet(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  function onDelete() {
    startTransition(async () => {
      const res = await deleteUser(user.id);
      if (res?.ok) {
        toast.success("User deleted");
        setOpenDelete(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0">
            <span className="sr-only">Open menu</span>
            <MoreHorizontal className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuLabel>Actions</DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={() => setOpenSheet(true)}>
            <Edit className="mr-2 h-4 w-4" />
            Edit
          </DropdownMenuItem>
          <DropdownMenuItem
            onClick={() => setOpenDelete(true)}
            className="text-red-600 focus:bg-red-50 focus:text-red-600"
          >
            <Trash className="mr-2 h-4 w-4" />
            Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <Sheet open={openSheet} onOpenChange={setOpenSheet}>
        <SheetContent className="!w-[40vw] sm:!max-w-[40vw] overflow-y-auto p-6">
          <SheetHeader>
            <SheetTitle>Edit User</SheetTitle>
          </SheetHeader>
          <form action={onUpdate} className="mt-8 grid grid-cols-2 gap-6">
            <input type="hidden" name="id" value={user.id} />
            <div className="space-y-2">
              <Label htmlFor="full_name">Full name *</Label>
              <Input
                id="full_name"
                name="full_name"
                defaultValue={user.full_name}
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input
                id="email"
                name="email"
                type="email"
                defaultValue={user.email}
                disabled
              />
              <p className="text-xs text-muted-foreground">Email cannot be changed here.</p>
            </div>
            <div className="space-y-2">
              <Label htmlFor="phone">Phone</Label>
              <Input id="phone" name="phone" defaultValue={user.phone || ""} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Update Password</Label>
              <div className="relative">
                <Input
                  id="password"
                  name="password"
                  type={showPassword ? "text" : "password"}
                  placeholder="Leave blank to keep current"
                />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="absolute right-0 top-0 h-9 w-9 text-muted-foreground"
                  onClick={() => setShowPassword(!showPassword)}
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  <span className="sr-only">Toggle password visibility</span>
                </Button>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="role_id">Role *</Label>
              <Select name="role_id" defaultValue={user.role_id} required>
                <SelectTrigger id="role_id">
                  <SelectValue placeholder="Select role" />
                </SelectTrigger>
                <SelectContent>
                  {roles.map((r) => (
                    <SelectItem key={r.id} value={r.id}>
                      {r.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="primary_branch_id">Branch *</Label>
              <Select
                name="primary_branch_id"
                defaultValue={user.primary_branch_id}
                required
              >
                <SelectTrigger id="primary_branch_id">
                  <SelectValue placeholder="Select branch" />
                </SelectTrigger>
                <SelectContent>
                  {branches.map((b) => (
                    <SelectItem key={b.id} value={b.id}>
                      {b.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="joining_date">Joining date</Label>
              <Input
                id="joining_date"
                name="joining_date"
                type="date"
                defaultValue={user.joining_date || ""}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="date_of_birth">Date of birth</Label>
              <Input
                id="date_of_birth"
                name="date_of_birth"
                type="date"
                defaultValue={user.date_of_birth || ""}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="b2b_country">B2B country</Label>
              <Input
                id="b2b_country"
                name="b2b_country"
                placeholder="Partners only"
                defaultValue={user.b2b_country || ""}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="b2b_state">B2B state</Label>
              <Input
                id="b2b_state"
                name="b2b_state"
                defaultValue={user.b2b_state || ""}
              />
            </div>
            <div className="col-span-2 space-y-2">
              <Label htmlFor="allowed_ips">Allowed IPs</Label>
              <Input
                id="allowed_ips"
                name="allowed_ips"
                placeholder="Comma-separated"
                defaultValue={
                  Array.isArray(user.allowed_ips)
                    ? user.allowed_ips.join(", ")
                    : user.allowed_ips || ""
                }
              />
            </div>
            <div className="col-span-2 flex justify-end pt-4">
              <Button type="submit" disabled={pending}>
                {pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {pending ? "Updating user..." : "Update user"}
              </Button>
            </div>
          </form>
        </SheetContent>
      </Sheet>

      <AlertDialog open={openDelete} onOpenChange={setOpenDelete}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the user{" "}
              <strong>{user.full_name}</strong> and remove their data from our servers.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={pending}>Cancel</AlertDialogCancel>
            <Button
              variant="destructive"
              onClick={onDelete}
              disabled={pending}
            >
              {pending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {pending ? "Deleting..." : "Delete user"}
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
