"use client"

import { useState, useEffect, useRef } from "react"
import { X, Eye, EyeOff, Loader2, Trash2, Camera } from "lucide-react"

export interface UserFormData {
  name: string
  email: string
  password: string
  role: "admin" | "employee"
  status?: "active" | "inactive"
  avatar?: File | null
  removeAvatar?: boolean
}

export interface EditUserFormData {
  name: string
  email: string
  password: string
  role: "admin" | "employee"
  status?: "active" | "inactive"
}

interface UserFormModalProps {
  open: boolean
  mode: "create" | "edit"
  initialData?: Partial<UserFormData> & { id?: string; image?: string }
  onClose: () => void
  onSubmit: (data: UserFormData) => Promise<void>
}

const MAX_AVATAR_SIZE_BYTES = 1 * 1024 * 1024

const EMPTY_FORM: UserFormData = {
  name: "",
  email: "",
  password: "",
  role: "employee",
  status: "active",
  avatar: null,
  removeAvatar: false,
}

function getInitials(name: string): string {
  return name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((n) => n[0].toUpperCase())
    .join("")
}

export function UserFormModal({
  open,
  mode,
  initialData,
  onClose,
  onSubmit,
}: UserFormModalProps) {
  const [form, setForm] = useState<UserFormData>(EMPTY_FORM)
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)
  const [avatarError, setAvatarError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (open) {
      if (mode === "edit" && initialData) {
        setForm({
          name: initialData.name ?? "",
          email: initialData.email ?? "",
          password: "",
          role: initialData.role ?? "employee",
          status: (initialData as any).status ?? "active",
          avatar: null,
          removeAvatar: false,
        })
      } else {
        setForm(EMPTY_FORM)
      }
      setShowPassword(false)
      setAvatarError(null)
    }
  }, [open, mode, initialData])

  useEffect(() => {
    if (form.avatar) {
      setIsUploading(true)
      const url = URL.createObjectURL(form.avatar)
      // Simulate a brief "uploading" delay for UX feedback
      const timer = setTimeout(() => {
        setPreviewUrl(url)
        setIsUploading(false)
      }, 500)
      return () => {
        clearTimeout(timer)
        URL.revokeObjectURL(url)
      }
    }

    if (mode === "edit" && initialData?.image && !form.removeAvatar) {
      setPreviewUrl(initialData.image)
    } else {
      setPreviewUrl(null)
    }
  }, [form.avatar, form.removeAvatar, mode, initialData])

  if (!open) return null

  function handleChange(field: keyof UserFormData, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }))
  }

  function handleFileChange(file?: File | null) {
    if (!file) return
    setAvatarError(null)
    if (!file.type.startsWith("image/")) {
      setAvatarError("Please choose a valid image file.")
      return
    }
    if (file.size > MAX_AVATAR_SIZE_BYTES) {
      setAvatarError("Avatar size must be 1 MB or less.")
      return
    }
    setForm((prev) => ({ ...prev, avatar: file, removeAvatar: false }))
  }

  function handleRemoveAvatar() {
    setForm((prev) => ({ ...prev, avatar: null, removeAvatar: true }))
    setPreviewUrl(null)
    if (fileInputRef.current) fileInputRef.current.value = ""
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setIsLoading(true)
    try {
      await onSubmit(form)
    } finally {
      setIsLoading(false)
    }
  }

  const isCreate = mode === "create"
  const hasAvatar = !!previewUrl && !isUploading
  const initials = getInitials(form.name) || "?"

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="user-modal-title"
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Modal */}
      <div className="relative w-full max-w-md bg-card rounded-2xl shadow-2xl border border-border overflow-hidden">
        {/* Header */}
        <div
          className="flex items-center justify-between px-6 py-5 border-b border-border"
          style={{ background: "var(--brand-navy)" }}
        >
          <div>
            <h2
              id="user-modal-title"
              className="text-white font-bold text-lg font-sans"
            >
              {isCreate ? "Create New User" : "Edit User"}
            </h2>
            <p className="text-white/50 text-xs font-sans mt-0.5">
              {isCreate
                ? "Add a new user to the system"
                : "Update user information"}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-xl cursor-pointer text-white/50 hover:text-white hover:bg-white/10 transition-colors"
            aria-label="Close"
            disabled={isLoading}
          >
            <X className="w-4 h-4" aria-hidden="true" />
          </button>
        </div>

        {/* Form */}
        <form
          onSubmit={handleSubmit}
          className="px-6 pt-7 pb-6 flex flex-col gap-5 max-h-[75vh] overflow-y-auto"
        >
          {/* ── Avatar Section ── */}
          <div className="flex flex-col items-center gap-2">
            {/* Hidden file input */}
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="sr-only"
              aria-label="Upload avatar"
              disabled={isLoading}
              onChange={(e) => handleFileChange(e.target.files?.[0])}
            />

            {/* Avatar circle + controls */}
            <div className="relative">
              {/* Clickable avatar */}
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={isLoading}
                aria-label="Change avatar"
                className="group relative w-24 h-24 rounded-full overflow-hidden border-4 border-white shadow-lg focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand-green)] transition-all"
              >
                {isUploading ? (
                  /* Loading state */
                  <div
                    className="w-full h-full flex items-center justify-center"
                    style={{ background: "var(--brand-navy)" }}
                  >
                    <Loader2 className="w-6 h-6 text-white animate-spin" aria-hidden="true" />
                  </div>
                ) : hasAvatar ? (
                  /* User image */
                  <img
                    src={previewUrl!}
                    alt="Avatar preview"
                    className="w-full h-full object-cover"
                  />
                ) : (
                  /* Initials fallback */
                  <div
                    className="w-full h-full flex items-center justify-center text-white text-2xl font-bold font-sans select-none"
                    style={{ background: "var(--brand-navy)" }}
                    aria-label={`Avatar initials: ${initials}`}
                  >
                    {initials}
                  </div>
                )}

                {/* Hover overlay */}
                {!isUploading && (
                  <div className="absolute inset-0 bg-black/0 group-hover:bg-black/45 transition-all duration-200 flex items-center justify-center">
                    <span className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex flex-col items-center gap-1">
                      <Camera className="w-5 h-5 text-white" aria-hidden="true" />
                      <span className="text-white text-[10px] font-semibold font-sans">
                        Change
                      </span>
                    </span>
                  </div>
                )}
              </button>

              {/* Delete button — only when an image exists */}
              {hasAvatar && (
                <button
                  type="button"
                  onClick={handleRemoveAvatar}
                  disabled={isLoading}
                  aria-label="Remove avatar"
                  className="absolute -top-1 -right-1 w-7 h-7 rounded-full bg-red-500 hover:bg-red-600 text-white flex items-center justify-center shadow-md transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400"
                >
                  <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
                </button>
              )}
            </div>

            <p className="text-xs text-muted-foreground font-sans">
              Click avatar to upload &mdash; PNG, JPG up to 1 MB
            </p>
            {avatarError && (
              <p className="text-xs font-sans text-red-500" role="alert">
                {avatarError}
              </p>
            )}
          </div>

          {/* ── Full Name ── */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-sm font-semibold text-foreground font-sans"
              htmlFor="uf-name"
            >
              Full Name
            </label>
            <input
              id="uf-name"
              type="text"
              required
              value={form.name}
              onChange={(e) => handleChange("name", e.target.value)}
              placeholder="Dr. Ahmet Yilmaz"
              disabled={isLoading}
              className="w-full px-4 py-2.5 rounded-xl border border-border bg-background text-foreground placeholder:text-muted-foreground text-sm font-sans outline-none transition-all focus:border-[var(--brand-green)] focus:ring-2 focus:ring-[var(--brand-green)]/20 disabled:opacity-60"
            />
          </div>

          {/* ── Email ── */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-sm font-semibold text-foreground font-sans"
              htmlFor="uf-email"
            >
              Email Address
            </label>
            <input
              id="uf-email"
              type="email"
              required
              value={form.email}
              onChange={(e) => handleChange("email", e.target.value)}
              placeholder="user@livist.com"
              disabled={isLoading}
              className="w-full px-4 py-2.5 rounded-xl border border-border bg-background text-foreground placeholder:text-muted-foreground text-sm font-sans outline-none transition-all focus:border-[var(--brand-green)] focus:ring-2 focus:ring-[var(--brand-green)]/20 disabled:opacity-60"
            />
          </div>

          {/* ── Password ── */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-sm font-semibold text-foreground font-sans"
              htmlFor="uf-password"
            >
              {isCreate ? "Password" : "New Password"}
              {!isCreate && (
                <span className="ml-1 text-xs font-normal text-muted-foreground">
                  (leave blank to keep current)
                </span>
              )}
            </label>
            <div className="relative">
              <input
                id="uf-password"
                type={showPassword ? "text" : "password"}
                required={isCreate}
                minLength={isCreate ? 8 : undefined}
                value={form.password}
                onChange={(e) => handleChange("password", e.target.value)}
                placeholder={
                  isCreate
                    ? "At least 8 characters"
                    : "Enter new password (optional)"
                }
                disabled={isLoading}
                className="w-full px-4 py-2.5 pr-11 rounded-xl border border-border bg-background text-foreground placeholder:text-muted-foreground text-sm font-sans outline-none transition-all focus:border-[var(--brand-green)] focus:ring-2 focus:ring-[var(--brand-green)]/20 disabled:opacity-60"
              />
              <button
                type="button"
                onClick={() => setShowPassword((v) => !v)}
                className="absolute cursor-pointer right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                aria-label={showPassword ? "Hide password" : "Show password"}
                tabIndex={-1}
              >
                {showPassword ? (
                  <EyeOff className="w-4 h-4" />
                ) : (
                  <Eye className="w-4 h-4" />
                )}
              </button>
            </div>
          </div>

          {/* ── Role ── */}
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-semibold text-foreground font-sans">
              Role
            </label>
            <div className="flex gap-3">
              {(["admin", "employee"] as const).map((role) => (
                <button
                  key={role}
                  type="button"
                  onClick={() => handleChange("role", role)}
                  disabled={isLoading}
                  className="flex-1 cursor-pointer py-2.5 rounded-xl text-sm font-semibold font-sans border transition-all duration-150 disabled:opacity-60"
                  style={
                    form.role === role
                      ? {
                          background:
                            role === "admin"
                              ? "var(--brand-navy)"
                              : "var(--brand-green)",
                          color: "white",
                          border: `2px solid ${
                            role === "admin"
                              ? "var(--brand-navy)"
                              : "var(--brand-green)"
                          }`,
                        }
                      : {
                          background: "transparent",
                          color: "var(--muted-foreground)",
                          border: "2px solid var(--border)",
                        }
                  }
                >
                  {role === "admin" ? "Admin" : "Staff"}
                </button>
              ))}
            </div>
          </div>

          {/* ── Status ── */}
          <div className="flex flex-col gap-1.5">
            <label className="text-sm font-semibold text-foreground font-sans">
              Status
            </label>
            <div className="flex gap-3">
              {(["active", "inactive"] as const).map((s) => (
                <button
                  key={s}
                  type="button"
                  onClick={() => handleChange("status", s)}
                  disabled={isLoading}
                  className="flex-1 py-2.5 cursor-pointer rounded-xl text-sm font-semibold font-sans border transition-all duration-150 disabled:opacity-60"
                  style={
                    form.status === s
                      ? {
                          background:
                            s === "active" ? "var(--brand-green)" : "#6B7280",
                          color: "white",
                          border: `2px solid ${
                            s === "active" ? "var(--brand-green)" : "#6B7280"
                          }`,
                        }
                      : {
                          background: "transparent",
                          color: "var(--muted-foreground)",
                          border: "2px solid var(--border)",
                        }
                  }
                >
                  {s === "active" ? "Active" : "Inactive"}
                </button>
              ))}
            </div>
          </div>

          {/* ── Actions ── */}
          <div className="flex gap-3 mt-1">
            <button
              type="button"
              onClick={onClose}
              disabled={isLoading}
              className="flex-1 cursor-pointer py-2.5 rounded-xl text-sm font-semibold font-sans border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-all disabled:opacity-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isLoading || isUploading}
              className="flex-1 cursor-pointer py-2.5 rounded-xl text-white text-sm font-semibold font-sans transition-all duration-150 flex items-center justify-center gap-2 disabled:opacity-70 hover:brightness-105"
              style={{ background: "var(--brand-green)" }}
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" aria-hidden="true" />
                  {isCreate ? "Creating..." : "Saving..."}
                </>
              ) : isCreate ? (
                "Create User"
              ) : (
                "Save Changes"
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
