"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card } from "@/components/ui/card"
import { KeyRound } from "lucide-react"
import { toast } from "@/hooks/use-toast"
import { useAuthStore, type User } from "@/lib/auth-store"
import {
  ERROR_FORMATO_PIN,
  PIN_LOGIN_DIGITOS as PIN_DIGITOS,
  esPinDeLogin,
  normalizarPin,
} from "@/lib/staff-pin-format"
import { getSedeById } from "@/lib/sedes-config"

/** Misma redirección por rol que usa el login. */
function destinoPorRol(user: User | null): string {
  const role = user?.role?.toUpperCase()
  const sede = user?.locationId ? getSedeById(user.locationId) : null
  if (role === "ADMIN") return "/admin/dashboard"
  if (role === "MANAGER" && sede) return `/admin/${sede.slug}`
  if (role === "EMPLOYEE" && sede) {
    return user?.username?.startsWith("cocina-")
      ? `/admin/${sede.slug}/cocina-display`
      : `/admin/${sede.slug}/pos`
  }
  return "/admin/dashboard"
}

export default function CambiarClavePage() {
  const router = useRouter()
  const user = useAuthStore((s) => s.user)
  const [form, setForm] = useState({ actual: "", nueva: "", confirmar: "" })
  const [isLoading, setIsLoading] = useState(false)

  const esPrimeraVez = Boolean(user?.mustChangePassword)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!esPinDeLogin(form.nueva)) {
      toast({ title: "PIN incompleto", description: ERROR_FORMATO_PIN, variant: "destructive" })
      return
    }
    // El PIN que reparte gerencia lo vio más de una persona: quedárselo no es
    // elegir el suyo. El servidor lo rechaza igual; acá se avisa sin viaje.
    if (form.nueva === form.actual) {
      toast({
        title: "Ese es el PIN que te dieron",
        description: "Elige uno distinto, que solo sepas tú.",
        variant: "destructive",
      })
      return
    }
    if (form.nueva !== form.confirmar) {
      toast({
        title: "No coinciden",
        description: "El PIN nuevo y su repetición no son iguales.",
        variant: "destructive",
      })
      return
    }
    setIsLoading(true)
    try {
      const res = await fetch("/api/auth/staff/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ currentPassword: form.actual, newPassword: form.nueva }),
      })
      const data = await res.json()
      if (!res.ok) {
        toast({
          title: "No se pudo cambiar el PIN",
          description: data.error || "Inténtalo de nuevo",
          variant: "destructive",
        })
        setIsLoading(false)
        return
      }
      // Apagar la bandera en el estado local para que AdminProtected lo deje pasar.
      const actual = useAuthStore.getState().user
      if (actual) {
        useAuthStore.setState({ user: { ...actual, mustChangePassword: false } })
      }
      toast({ title: "PIN actualizado", description: "Ya puedes seguir trabajando." })
      router.push(destinoPorRol(actual))
    } catch {
      toast({
        title: "Error de conexión",
        description: "No se pudo conectar con el servidor",
        variant: "destructive",
      })
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4">
      <Card className="w-full max-w-md p-8">
        <div className="flex flex-col items-center mb-6 text-center">
          <div className="h-12 w-12 rounded-full bg-verde-bosque/10 flex items-center justify-center mb-3">
            <KeyRound className="h-6 w-6 text-verde-bosque" />
          </div>
          <h1 className="font-heading text-2xl text-verde-bosque">
            {esPrimeraVez ? "Elige tu PIN" : "Cambiar mi PIN"}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {esPrimeraVez
              ? `Hola${user?.name ? ` ${user.name}` : ""}: el PIN que te dieron es temporal y lo vio más de una persona. Elige el tuyo para continuar.`
              : "Necesitas tu PIN actual para elegir uno nuevo."}
          </p>
        </div>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="clave-actual">PIN actual</Label>
            <Input
              id="clave-actual"
              type="password"
              inputMode="numeric"
              autoComplete="current-password"
              maxLength={PIN_DIGITOS}
              value={form.actual}
              onChange={(e) => setForm({ ...form, actual: normalizarPin(e.target.value) })}
              required
            />
          </div>
          <div>
            <Label htmlFor="clave-nueva">PIN nuevo</Label>
            <Input
              id="clave-nueva"
              type="password"
              inputMode="numeric"
              autoComplete="new-password"
              maxLength={PIN_DIGITOS}
              value={form.nueva}
              onChange={(e) => setForm({ ...form, nueva: normalizarPin(e.target.value) })}
              required
            />
            <p className="text-xs text-muted-foreground mt-1">
              {PIN_DIGITOS} dígitos, solo números — sin letras. Con este PIN entras al panel, sin
              usuario. No lo compartas, y que no sea otro que ya use un compañero.
            </p>
          </div>
          <div>
            <Label htmlFor="clave-confirmar">Repite el PIN nuevo</Label>
            <Input
              id="clave-confirmar"
              type="password"
              inputMode="numeric"
              autoComplete="new-password"
              maxLength={PIN_DIGITOS}
              value={form.confirmar}
              onChange={(e) => setForm({ ...form, confirmar: normalizarPin(e.target.value) })}
              required
            />
          </div>
          <Button
            type="submit"
            disabled={isLoading}
            className="w-full bg-verde-neon text-verde-bosque hover:bg-verde-neon/90"
          >
            {isLoading ? "Guardando…" : "Guardar mi PIN"}
          </Button>
        </form>
      </Card>
    </div>
  )
}
