"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { updateUser } from "@/actions/users";
import { useToast } from "@/components/ui/use-toast";
import { Eye, EyeOff, ShieldAlert } from "lucide-react";

export interface EditableUser {
  id: string;
  name: string | null;
  email: string;
  role: string;
  isActive: boolean;
}

interface EditUserDialogProps {
  user: EditableUser;
  isSelf: boolean;
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

export function EditUserDialog({ user, isSelf, open, onClose, onSuccess }: EditUserDialogProps) {
  const { toast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [form, setForm] = useState({
    name: user.name ?? "",
    role: user.role,
    isActive: user.isActive,
    newPassword: "",
  });
  const [passwordError, setPasswordError] = useState("");

  const set = <K extends keyof typeof form>(key: K, value: typeof form[K]) => {
    setForm((f) => ({ ...f, [key]: value }));
    if (key === "newPassword") setPasswordError("");
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.newPassword && form.newPassword.length < 8) {
      setPasswordError("At least 8 characters");
      return;
    }
    setIsSubmitting(true);
    try {
      await updateUser({
        userId: user.id,
        name: form.name || undefined,
        role: form.role as "ADMIN" | "PRODUCER" | "SUPERVISOR" | "ARTIST" | "CLIENT",
        isActive: form.isActive,
        newPassword: form.newPassword || undefined,
      });
      toast({ title: "User updated" });
      onSuccess?.();
      onClose();
    } catch (err) {
      toast({ title: "Failed to update user", description: err instanceof Error ? err.message : undefined, variant: "destructive" });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Edit User</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4 py-2">
          {/* Read-only email */}
          <div className="space-y-1.5">
            <Label className="text-zinc-400">Email</Label>
            <p className="text-sm text-zinc-300 bg-zinc-900 border border-zinc-800 rounded-md px-3 py-2">{user.email}</p>
          </div>

          <div className="space-y-1.5">
            <Label>Name <span className="text-zinc-500 font-normal">(optional)</span></Label>
            <Input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Jane Smith" />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label>Role</Label>
              <Select value={form.role} onValueChange={(v) => set("role", v)} disabled={isSelf}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="ADMIN">Admin</SelectItem>
                  <SelectItem value="PRODUCER">Producer</SelectItem>
                  <SelectItem value="SUPERVISOR">Supervisor</SelectItem>
                  <SelectItem value="ARTIST">Artist</SelectItem>
                  <SelectItem value="CLIENT">Client</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-1.5">
              <Label>Status</Label>
              <Select
                value={form.isActive ? "active" : "inactive"}
                onValueChange={(v) => set("isActive", v === "active")}
                disabled={isSelf}
              >
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {isSelf && (
            <p className="flex items-center gap-1.5 text-xs text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-md px-3 py-2">
              <ShieldAlert className="h-3.5 w-3.5 shrink-0" />
              You cannot change your own role or deactivate yourself.
            </p>
          )}

          <Separator />

          {/* Password reset */}
          <div className="space-y-1.5">
            <Label>New Password <span className="text-zinc-500 font-normal">(leave blank to keep current)</span></Label>
            <div className="relative">
              <Input
                type={showPassword ? "text" : "password"}
                value={form.newPassword}
                onChange={(e) => set("newPassword", e.target.value)}
                placeholder="Min. 8 characters"
                autoComplete="new-password"
                className="pr-10"
              />
              <button
                type="button"
                onClick={() => setShowPassword((s) => !s)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-200"
                tabIndex={-1}
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>
            {passwordError && <p className="text-xs text-destructive">{passwordError}</p>}
          </div>

          <DialogFooter className="pt-2">
            <Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Saving…" : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
