'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { TextField, Button, Alert, CircularProgress } from '@mui/material'
import Image from 'next/image'
import Link from 'next/link'

function Login() {
  const router = useRouter()
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const textFieldStyle = {
    backgroundColor: 'white',
    borderRadius: '50px',
    '& .MuiInputBase-root': {
      borderRadius: '55px',
    },
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    e.stopPropagation()
    
    // Validate inputs
    if (!name || !email || !password) {
      setError('Please enter both email and password')
      return
    }

    setError('')
    setLoading(true)

    try {
      const response = await fetch('/api/signup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, email, password }),
      })

      const data = await response.json()

      if (!response.ok) {
        setError(data.error || 'Signup failed. Please try again.')
        setLoading(false)
        return
      }

      // Signup successful - wait a moment for cookie to be set, then redirect
      // Using setTimeout to ensure cookie is set before navigation
      setTimeout(() => {
        router.push('/amazon-api-user-dashboard')
      }, 200)
    } catch (err) {
      setError('An error occurred. Please try again.')
      setLoading(false)
      console.error('Signup error:', err)
    }
  }

  return (
    <main className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <section className="w-full max-w-md lg:pt-20">
        <div className="bg-white rounded-lg shadow-lg p-4 lg:p-8">
          <div className="text-center mb-4 lg:mb-8">
          <Image
              className="w-[100px] md:w-[100px] h-auto mx-auto mb-5"
              src="/assets/img/eleantz-logo.webp"
              alt="logo"
              width={150}
              height={82}
            />
            <h1 className="text-3xl font-bold text-gray-900 mb-2">Sign Up</h1>
            <p className="text-gray-600">Sign up to access your dashboard</p>
          </div>

          {error && (
            <Alert severity="error" className="mb-6" onClose={() => setError('')}>
              {error}
            </Alert>
          )}

          <form onSubmit={handleSubmit} className="space-y-3" noValidate>
            <div>
              <TextField
                fullWidth
                id="name"
                label="Name"
                type="text"
                variant="outlined"
                size="small"
                required
                value={name}
                onChange={(e) => setName(e.target.value)}
                disabled={loading}
                sx={textFieldStyle}
              />
            </div>

            <div>
              <TextField
                fullWidth
                id="email"
                label="Email or Username"
                type="text"
                variant="outlined"
                size="small"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                disabled={loading}
                sx={textFieldStyle}
              />
            </div>

            <div>
              <TextField
                fullWidth
                id="password"
                label="Password"
                type="password"
                variant="outlined"
                size="small"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                disabled={loading}
                sx={textFieldStyle}
              />
            </div>

            <Button
              type="submit"
              fullWidth
              variant="contained"
              disabled={loading}
              sx={{
                borderRadius: '50px',
                padding: '10px',
                fontSize: '16px',
                fontWeight: 'bold',
                textTransform: 'none',
                backgroundColor: '#c4262e',
                '&:hover': {
                  backgroundColor: '#c4262e',
                },
              }}
            >
              {loading ? (
                <CircularProgress size={24} color="inherit" />
              ) : (
                'Sign In'
              )}
            </Button>
          </form>

          <br/>
          <hr className='opacity-5'/>
          <br/>
          <div className='text-center'>
              I have an account? <Link href='/amazon/login' className='text-[#c4262e] cursor-pointer'>Sign In</Link>
          </div>
        </div>
      </section>
    </main>
  )
}

export default Login