"use client";

import { useState, type FormEvent } from "react";
import {
  Vote,
  Lock,
  User,
  Loader2,
  AlertCircle,
  ShieldCheck,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
  CardFooter,
} from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { useAuthStore, type AuthUser } from "@/store/auth-store";

export function LoginForm() {
  const [employeeId, setEmployeeId] = useState("");
  const [pin, setPin] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const setUser = useAuthStore((s) => s.setUser);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError("");

    if (!employeeId.trim()) {
      setError("กรุณาระบุรหัสพนักงาน");
      return;
    }
    if (!pin.trim()) {
      setError("กรุณาระบุ PIN");
      return;
    }

    setIsLoading(true);
    try {
      const res = await fetch("/api/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          employeeId: employeeId.trim(),
          pin: pin.trim(),
        }),
      });

      const data = await res.json();

      if (!data.success) {
        setError(data.error || "เข้าสู่ระบบไม่สำเร็จ");
        return;
      }

      const user: AuthUser = {
        employeeId: data.user.employeeId,
        name: data.user.name,
        branchId: data.user.branchId,
        branchName: data.user.branchName,
        isAdmin: data.user.isAdmin,
        dbId: data.user.dbId ?? "",
      };
      setUser(user);
    } catch {
      setError("ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์ได้");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center w-full justify-center p-4 bg-gradient-to-br from-emerald-50 via-white to-teal-50 relative overflow-hidden">
      {/* Decorative background elements */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-80 h-80 rounded-full bg-emerald-100/50 blur-3xl" />
        <div className="absolute -bottom-40 -left-40 w-80 h-80 rounded-full bg-teal-100/50 blur-3xl" />
        <div className="absolute top-1/4 left-1/4 w-2 h-2 rounded-full bg-emerald-300/60" />
        <div className="absolute top-1/3 right-1/3 w-3 h-3 rounded-full bg-teal-300/40" />
        <div className="absolute bottom-1/4 right-1/4 w-2 h-2 rounded-full bg-emerald-400/50" />
      </div>

      <Card className="w-full max-w-md relative shadow-xl border-emerald-100/60 bg-white/95 backdrop-blur-sm">
        <CardHeader className="text-center space-y-4 pb-2">
          {/* Logo / Icon */}
          <div className="mx-auto flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg shadow-emerald-200/50">
            <Vote className="w-8 h-8 text-white" />
          </div>

          <div className="space-y-2">
            <CardTitle className="text-2xl font-bold text-gray-900 tracking-tight">
              ระบบเลือกตั้งตัวแทนพนักงาน
            </CardTitle>
            <CardDescription className="text-gray-500 text-sm">
              กรุณาเข้าสู่ระบบด้วยรหัสพนักงาน
            </CardDescription>
          </div>
        </CardHeader>

        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Error message */}
            {error && (
              <div className="flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm animate-in fade-in slide-in-from-top-1 duration-300">
                <AlertCircle className="w-4 h-4 shrink-0" />
                <span>{error}</span>
              </div>
            )}

            {/* Employee ID field */}
            <div className="space-y-2">
              <Label htmlFor="employeeId" className="text-gray-700 font-medium">
                รหัสพนักงาน
              </Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <Input
                  id="employeeId"
                  type="text"
                  placeholder="เช่น 025XX"
                  value={employeeId}
                  onChange={(e) => setEmployeeId(e.target.value)}
                  className="pl-10 h-11 border-gray-200 focus-visible:border-emerald-500 focus-visible:ring-emerald-500/20"
                  disabled={isLoading}
                  autoComplete="username"
                />
              </div>
            </div>

            {/* PIN field */}
            <div className="space-y-2">
              <Label htmlFor="pin" className="text-gray-700 font-medium">
                PIN
              </Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <Input
                  id="pin"
                  type="password"
                  placeholder="กรอก PIN 4 หลัก"
                  value={pin}
                  onChange={(e) => setPin(e.target.value)}
                  maxLength={4}
                  className="pl-10 h-11 border-gray-200 focus-visible:border-emerald-500 focus-visible:ring-emerald-500/20"
                  disabled={isLoading}
                  autoComplete="current-password"
                />
              </div>
            </div>

            {/* Submit button */}
            <Button
              type="submit"
              disabled={isLoading}
              className="w-full h-11 text-base font-semibold bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 shadow-md shadow-emerald-200/50 transition-all duration-200 cursor-pointer"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  กำลังเข้าสู่ระบบ...
                </>
              ) : (
                "เข้าสู่ระบบ"
              )}
            </Button>
          </form>
        </CardContent>

        <CardFooter className="justify-center pb-6">
          <div className="flex items-center gap-1.5 text-xs text-gray-400 bg-gray-50 px-4 py-2.5 rounded-lg border border-gray-100">
            <ShieldCheck className="w-3.5 h-3.5 text-amber-500" />

            {/* <span className="font-mono font-medium text-gray-600">
              ADMIN001
            </span>
            <span>/</span>
            <span className="font-mono font-medium text-gray-600">1234</span>
            <span className="text-amber-600 font-medium">(Admin)</span>
            <span className="mx-1">หรือ</span>
            <span className="font-mono font-medium text-gray-600">EMP001</span>
            <span>/</span>
            <span className="font-mono font-medium text-gray-600">1234</span>
            <span className="text-emerald-600 font-medium">(พนักงาน)</span> */}
          </div>
        </CardFooter>
      </Card>
    </div>
  );
}
