'use client'
import React, { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import axios from 'axios'
import TopNavOne from '@/components/Header/TopNav/TopNavOne'
import MenuOne from '@/components/Header/Menu/MenuOne'
import Breadcrumb from '@/components/Breadcrumb/Breadcrumb'
import Footer from '@/components/Footer/Footer'
import * as Icon from "@phosphor-icons/react/dist/ssr";
import { BaseURL } from '../../../utils/BaseUrl'
import { useCart } from '@/context/CartContext'


const Login = () => {
  const router = useRouter()
  const { refreshCart } = useCart()

  const [form, setForm] = useState({
    email: '',
    password: '',
    remember: false,
  })
  const [errors, setErrors] = useState<{ [k: string]: string }>({})
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    setForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }))
  }

  const validate = () => {
    const errs: { [k: string]: string } = {}
    if (!form.email.trim()) errs.email = 'Email is required'
    if (!form.password) errs.password = 'Password is required'
    return errs
  }

  const handleSubmit = async (e: React.FormEvent | React.MouseEvent) => {
    e.preventDefault()
    if (isSubmitting) return

    const v = validate()
    setErrors(v)
    if (Object.keys(v).length > 0) return

    setIsSubmitting(true)
    const body = {
      email: form.email,
      password: form.password,
    }

    try {
      const res: any = await axios.post(`${BaseURL}/auth/login`, body)

      localStorage.setItem('token', res?.data?.token)
      localStorage.setItem('user', res?.data?.user)
      // reset errors if any
      setErrors({})
      // 🔹 Refresh cart immediately after login
      await refreshCart()
      router.push('/')

    } catch (err: any) {
      console.log('login error:', err)
      let msg = 'Login failed'
      if (err?.response?.data) {
        msg =
          err.response.data.message ||
          err.response.data.error ||
          JSON.stringify(err.response.data) ||
          msg
      } else if (err?.message) {
        msg = err.message
      }
      setErrors(prev => ({ ...prev, submit: msg }))
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <>
      <TopNavOne props="style-one bg-black" slogan="New customers save 10% with the code GET10" />
      <div id="header" className="relative w-full">
        <MenuOne props="bg-transparent" />
        <Breadcrumb heading="Login" subHeading="Login" />
      </div>
      <div className="login-block md:py-20 py-10">
        <div className="container">
          <div className="content-main flex gap-y-8 max-md:flex-col">
            <div className="left md:w-1/2 w-full lg:pr-[60px] md:pr-[40px] md:border-r border-line">
              <div className="heading4">Login</div>
              <form className="md:mt-7 mt-4" noValidate>
                <div className="email ">
                  <input
                    className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                    id="email"
                    name="email"
                    type="email"
                    placeholder="Username or email address *"
                    value={form.email}
                    onChange={handleChange}
                    required
                    aria-invalid={!!errors.email}
                    aria-describedby="error-email"
                  />
                  {errors.email && (
                    <div id="error-email" className="text-danger mt-1">
                      {errors.email}
                    </div>
                  )}
                </div>
                <div className="pass mt-5">
                  <input
                    className="border-line px-4 pt-3 pb-3 w-full rounded-lg"
                    id="password"
                    name="password"
                    type="password"
                    placeholder="Password *"
                    value={form.password}
                    onChange={handleChange}
                    required
                    aria-invalid={!!errors.password}
                    aria-describedby="error-password"
                  />
                  {errors.password && (
                    <div id="error-password" className="text-danger mt-1">
                      {errors.password}
                    </div>
                  )}
                </div>
                <div className="flex items-center justify-between mt-5">
                  <div className="flex items-center">
                    <div className="block-input relative">
                      <input
                        type="checkbox"
                        name="remember"
                        id="remember"
                        checked={form.remember}
                        onChange={handleChange}
                        className="opacity-0 absolute inset-0 z-10 cursor-pointer"
                      />
                      <Icon.CheckSquare size={20} weight="fill" className="icon-checkbox" />
                    </div>
                    <label htmlFor="remember" className="pl-2 cursor-pointer">
                      Remember me
                    </label>
                  </div>
                  <Link href={'/forgot-password'} className="font-semibold hover:underline">
                    Forgot Your Password?
                  </Link>
                </div>

                {errors.submit && (
                  <div className="text-danger mt-3" role="alert">
                    {errors.submit}
                  </div>
                )}

                <div className="block-button md:mt-7 mt-4">
                  <a
                    href="#"
                    onClick={(e) => handleSubmit(e)}
                    role="button"
                    className={`button-main block-button inline-block text-center ${isSubmitting ? 'opacity-50 pointer-events-none' : ''
                      }`}
                    aria-label="Login"
                  >
                    {isSubmitting ? 'Logging in...' : 'Login'}
                  </a>
                </div>
              </form>
            </div>

            <div className="right md:w-1/2 w-full lg:pl-[60px] md:pl-[40px] flex items-center">
              <div className="text-content">
                <div className="heading4">New Customer</div>
                <div className="mt-2 text-secondary">
                  Be part of our growing family of new customers! Join us today and unlock a world of exclusive benefits,
                  offers, and personalized experiences.
                </div>
                <div className="block-button md:mt-7 mt-4">
                  <Link href={'/register'} className="button-main">
                    Register
                  </Link>
                </div>
              </div>
            </div>

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

export default Login
