import {
  Box,
  Card,
  Typography,
  Button,
  Link,
  Divider,
  Container,
  Dialog,
  DialogContent,
  Zoom,
  Fade,
} from '@mui/material'
import { useState } from 'react'
import MuiDynamicInput from '../../utills/MuiDynamicInput.jsx'
import CheckCircleIcon from '@mui/icons-material/CheckCircle'
import { keyframes } from '@mui/system'


// Define keyframe animations
const scaleIn = keyframes`
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
`

const checkmarkDraw = keyframes`
  0% {
    stroke-dashoffset: 100;
  }
  100% {
    stroke-dashoffset: 0;
  }
`

const pulse = keyframes`
  0% {
    box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.4);
  }
  70% {
    box-shadow: 0 0 0 20px rgba(76, 175, 80, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
  }
`

const fadeInUp = keyframes`
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
`

// Success Modal Component
function SuccessModal({ open, onClose, title, message }) {
  return (
    <Dialog
      open={open}
      onClose={onClose}
      TransitionComponent={Zoom}
      TransitionProps={{ timeout: 400 }}
      PaperProps={{
        sx: {
          borderRadius: 4,
          minWidth: { xs: 280, sm: 400 },
          overflow: 'visible',
        },
      }}
    >
      <DialogContent
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          py: 5,
          px: 4,
          textAlign: 'center',
        }}
      >
        {/* Animated Success Icon */}
        <Box
          sx={{
            width: 100,
            height: 100,
            borderRadius: '50%',
            backgroundColor: 'success.light',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            animation: `${scaleIn} 0.5s ease-out, ${pulse} 1.5s ease-out 0.5s`,
            mb: 3,
          }}
        >
          <CheckCircleIcon
            sx={{
              fontSize: 60,
              color: 'success.main',
              animation: `${scaleIn} 0.6s ease-out 0.2s both`,
            }}
          />
        </Box>

        {/* Success Title */}
        <Fade in={open} timeout={800}>
          <Typography
            variant="h5"
            sx={{
              fontWeight: 700,
              color: 'success.main',
              mb: 1,
              animation: `${fadeInUp} 0.5s ease-out 0.3s both`,
            }}
          >
            {title || 'Success!'}
          </Typography>
        </Fade>

        {/* Success Message */}
        <Fade in={open} timeout={1000}>
          <Typography
            variant="body1"
            sx={{
              color: 'text.secondary',
              mb: 3,
              animation: `${fadeInUp} 0.5s ease-out 0.5s both`,
            }}
          >
            {message || 'Your action was completed successfully.'}
          </Typography>
        </Fade>

        {/* Continue Button */}
        <Fade in={open} timeout={1200}>
          <Button
            variant="contained"
            onClick={onClose}
            sx={{
              mt: 1,
              px: 5,
              py: 1.5,
              borderRadius: 50,
              backgroundColor: 'success.main',
              fontWeight: 600,
              textTransform: 'none',
              fontSize: '1rem',
              animation: `${fadeInUp} 0.5s ease-out 0.7s both`,
              '&:hover': {
                backgroundColor: 'success.dark',
              },
            }}
          >
            Continue
          </Button>
        </Fade>
      </DialogContent>
    </Dialog>
  )
}
const LoginPanel = () => {

    const [formData, setFormData] = useState({
    emailOrMobile: '',
    password: '',
    keepLoggedIn: false,
  })

  const [errors, setErrors] =useState({})
  const [loading, setLoading] = useState(false)
 const [successModal, setSuccessModal] = useState(false)
  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData((prev) => ({ ...prev, [name]: value }))
    // Clear error when user types
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: '' }))
    }
  }

  const validateForm = () => {
    const newErrors = {}

    if (!formData.emailOrMobile) {
      newErrors.emailOrMobile = 'Email or Mobile Number is required'
    } else if (
      !/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(formData.emailOrMobile) &&
      !/^\d{10}$/.test(formData.emailOrMobile)
    ) {
      newErrors.emailOrMobile = 'Enter a valid email or 10-digit mobile number'
    }

    if (!formData.password) {
      newErrors.password = 'Password is required'
    } else if (formData.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async () => {
    if (!validateForm()) return

    setLoading(true)
    // Simulate API call
    setTimeout(() => {
      setLoading(false)
      setSuccessModal(true) // Show success modal
      console.log('Form Data:', formData)
    }, 1500)
  }

  const handleCloseSuccessModal = () => {
    setSuccessModal(false)
    // Reset form after successful login
    setFormData({
      emailOrMobile: '',
      password: '',
      keepLoggedIn: false,
    })
    // Navigate to dashboard or next page
    console.log('Navigate to dashboard...')
  }

  const handleOTPLogin = () => {
    console.log('Navigate to OTP Login')
  }

  const handleForgotPassword = () => {
    console.log('Navigate to Forgot Password')
  }


  return (
    <>

   <Container maxWidth="sm" sx={{ py: 4 }}>
      <Card
        elevation={8}
        sx={{
          borderRadius: 4,
          overflow: 'hidden',
        }}
      >
        {/* Header */}
        <Box
          sx={{
            background: 'linear-gradient(135deg, #034E08 0%, #034E08 100%)',
            py: 3,
            px: 4,
          }}
        >
          <Typography
            variant="h5"
            component="h1"
            sx={{
              color: 'white',
              fontWeight: 600,
              textAlign: 'center',
            }}
          >
            Member Login
          </Typography>
        </Box>

        {/* Form Content */}
        <Box sx={{ p: 4 }}>
          {/* Email or Mobile Input */}
          <MuiDynamicInput
            type="text"
            name="emailOrMobile"
            label="E-mail or Mobile Number"
            value={formData.emailOrMobile}
            onChange={handleChange}
            error={errors.emailOrMobile}
            autoFocus
            required
          />

          {/* Password Input */}
          <MuiDynamicInput
            type="password"
            name="password"
            label="Password"
            value={formData.password}
            onChange={handleChange}
            error={errors.password}
            showPasswordToggle
            required
          />

          {/* Keep me logged in Checkbox */}
          <MuiDynamicInput
            type="checkbox"
            name="keepLoggedIn"
            label="Keep me logged in"
            value={formData.keepLoggedIn}
            onChange={handleChange}
            color="success"
          />

          {/* Login Button */}
          <Button
            fullWidth
            variant="contained"
            onClick={handleSubmit}
            disabled={loading}
            sx={{
              mt: 2,
              py: 1.5,
              borderRadius: 50,
              backgroundColor: '#A70710',
              fontSize: '1rem',
              fontWeight: 600,
              textTransform: 'uppercase',
              boxShadow: '0 4px 12px rgba(255, 0, 0, 0.4)',
              '&:hover': {
                backgroundColor: '#A70710',
                boxShadow: '0 6px 16px rgba(255, 0, 0, 0.5)',
              },
              '&:disabled': {
                backgroundColor: '#923237ff',
              },
            }}
          >
            {loading ? 'Logging in...' : 'LOGIN'}
          </Button>

          {/* Trouble logging in section */}
          <Box sx={{ mt: 4, textAlign: 'center' }}>
            <Typography
              variant="subtitle1"
              sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}
            >
              Trouble logging in?
            </Typography>

            <Box
              sx={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                gap: 1,
              }}
            >
              <Link
                component="button"
                variant="body2"
                onClick={handleOTPLogin}
                sx={{
                  color: '#A70710',
                  fontWeight: 500,
                  textDecoration: 'none',
                  '&:hover': {
                    textDecoration: 'underline',
                    color: '#A70710',
                  },
                }}
              >
                Login with OTP
              </Link>

              <Divider orientation="vertical" flexItem sx={{ mx: 1 }} />

              <Link
                component="button"
                variant="body2"
                onClick={handleForgotPassword}
                sx={{
                  color: '#A70710',
                  fontWeight: 500,
                  textDecoration: 'none',
                  '&:hover': {
                    textDecoration: 'underline',
                    color: '#A70710',
                  },
                }}
              >
                Forgot Password?
              </Link>
            </Box>
          </Box>
        </Box>
      </Card>
 {/* Animated Success Modal */}
      <SuccessModal
        open={successModal}
        onClose={handleCloseSuccessModal}
        title="Login Successful!"
        message="Welcome back! You have been logged in successfully."
      />
     
    </Container>

    </>
  )
}

export default LoginPanel
