"use client"

import type React from "react"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Eye, EyeOff, Shield, Lock, Mail, CheckCircle, LoaderCircle } from "lucide-react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { LogIn } from "@/lib/features/login/service"

import { useRouter } from "next/navigation";
import { setAuthCookie } from "@/lib/features/login/session"
import { LoginProps } from "@/lib/features/login/type"

export default function Login() {
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)

  const [username, setUsername] = useState('')
  const [pass, setPass] = useState('')

  const [message, setMessage] = useState('')

  const queryClient = useQueryClient();
  const router = useRouter();

  const mutation = useMutation({
    mutationFn: LogIn,
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["login-form"] }); // Refetch items after creating

      const response = data as unknown as LoginProps;

      if (response?.data?.token) {

        setIsLoading(false)
        setAuthCookie(response?.data.token, "pharma_token");

        //router.push("/");
        //window.location.href = "/";
        router.refresh() // This refreshes the current route and updates server components
        //router.push("/my")
        router.push("/dashboard")


        return false;
      } else {

        setMessage("Username or Password is invalid")
        setIsLoading(false)
        return false
      }




    },
    onError: (error) => {

      console.log("Error", error)

      setIsLoading(false);
      setMessage("Something went wrong, try again")
      return false;
    },
  });

  function onSubmit() {

    setMessage('');

    if (username === null || username === '') {
      setMessage("Username is required")
      return false;
    }

    else if (pass === null || pass === '') {
      setMessage("Password is required")
      return false;
    } else {

      setIsLoading(true)
      const body = {
        username: username,
        pass: pass,
        language: 1

      };
      mutation.mutate(body);

    }

  }



  return (
    <div className="min-h-screen bg-gradient-to-br from-green-50 via-emerald-50 to-teal-50 flex items-center justify-center p-4">
      <div className="w-full max-w-6xl grid lg:grid-cols-2 gap-8 items-center">
        {/* Left Side - Branding & Info */}
        <div className="hidden lg:block space-y-4">
          <div className="space-y-6">
            <div className="flex items-center space-x-3">

              <div>
                <h1 className="text-3xl font-bold text-gray-900">BK Pro League</h1>
                <p className="text-gray-600"></p>
              </div>
            </div>

            <div className="space-y-4">
              <h2 className="text-2xl font-bold text-gray-900">Welcome Back!</h2>
            </div>

            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <div style={{ backgroundColor: '#1B3261' }} className="p-2 rounded-lg">
                  <Shield className="h-5 w-5 text-white" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">Secure & Private</h3>
                  <p className="text-sm text-gray-600"></p>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <div style={{ backgroundColor: '#1B3261' }} className="p-2 rounded-lg">
                  <CheckCircle className="h-5 w-5 text-white" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">24/7 Access</h3>
                  <p className="text-sm text-gray-600"></p>
                </div>
              </div>


            </div>
          </div>


        </div>

        {/* Right Side - Login Form */}
        <div className="w-full max-w-md mx-auto lg:mx-0">
          {/* Mobile Header */}
          <div className="lg:hidden text-center mb-8">
            <p className="text-gray-600">Sign in to your account</p>
          </div>

          <Card className="shadow-xl border-0">
            <CardHeader className="space-y-4">

              <div>
                <CardTitle className="text-2xl font-bold text-gray-900">Sign In</CardTitle>
              </div>

              {message ? <p className="text-red-500 text-center">{message}</p> : ""}

            </CardHeader>

            <CardContent>
              <form className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="username" className="text-sm font-medium">
                    Username
                  </Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <Input id="username" type="text" placeholder="" className="pl-10" required
                      value={username} onChange={(e) => setUsername(e.target.value)}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="password" className="text-sm font-medium">
                    Password
                  </Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      placeholder="Enter your password"
                      className="pl-10 pr-10"
                      required
                      value={pass} onChange={(e) => setPass(e.target.value)}
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                </div>

                <Button
                  onClick={() => onSubmit()}
                  type="button"
                  style={{ backgroundColor: '#1B3261' }}
                  className="w-ful hover:bg-green-700 text-white py-2.5"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <LoaderCircle className="animate-spin" />
                  ) : (
                    "Sign In"
                  )}
                </Button>


              </form>

            </CardContent>
          </Card>

        </div>
      </div>
    </div>
  )
}
