
import React, { useState, useEffect } from 'react';
import { useBranding } from '../context/BrandingContext';
import { Mail, Lock, User, MapPin, Phone, Globe, ChevronRight, AlertCircle, CheckCircle2, ArrowLeft } from 'lucide-react';
import { validateLogin, registerClient, sendPasswordResetEmail } from '../services/whmcsService';

interface LoginViewProps {
  onLogin: (clientId: number, rememberMe: boolean, userId?: number, email?: string) => void;
}

const LoginView: React.FC<LoginViewProps> = ({ onLogin }) => {
  const [isRegister, setIsRegister] = useState(false);
  const { branding } = useBranding();
  const [isForgot, setIsForgot] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [resetEmail, setResetEmail] = useState('');
  const [resetStatus, setResetStatus] = useState<'idle' | 'success'>('idle');

  // Login State
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);

  // Register State
  const [regData, setRegData] = useState({
    firstname: '',
    lastname: '',
    email: '',
    password: '',
    address1: '',
    city: '',
    state: '',
    postcode: '',
    country: 'BD',
    phonenumber: ''
  });

  const handleRegChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setRegData({ ...regData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      if (isRegister) {
        const res = await registerClient(regData);
        if (res.result === 'success' && res.clientid) {
          onLogin(Number(res.clientid), false, undefined, regData.email);
        } else {
          setError(res.message || 'Registration failed. Please check your details.');
        }
      } else {
        const res = await validateLogin(email, password);
        if (res.result === 'success' && res.userid) {
          onLogin(Number(res.userid), rememberMe, res.auth_user_id, email);
        } else {
          setError(res.message || 'Login failed. Please check your credentials.');
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Connection error. Please try again later.');
    } finally {
      setLoading(false);
    }
  };

  const handleResetSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const res = await sendPasswordResetEmail(resetEmail);
      if (res.result === 'success') {
        setResetStatus('success');
      } else {
        setError(res.message || 'Failed to send reset email.');
      }
    } catch (err) {
      setError('Connection error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  // Slider State
  const [currentSlide, setCurrentSlide] = useState(0);
  const slides = branding?.loginSlides || [];
  const hasSlides = slides.length > 0;

  useEffect(() => {
    if (!hasSlides) return;
    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
    }, 5000);
    return () => clearInterval(timer);
  }, [hasSlides, slides.length]);

  const activeSlide = hasSlides ? slides[currentSlide] : {
    image: "https://images.unsplash.com/photo-1556761175-5973dc0f32e7?q=80&w=2664&auto=format&fit=crop",
    title: "Our people make the difference",
    subtitle: branding?.loginSubtitle || `When you need support or have a question, ${branding?.appName || 'CloudCore'} Experts have the answers.`
  };

  return (
    <div className="min-h-screen flex bg-white font-sans">
      {/* Left Side - Hero / Slider */}
      <div className="hidden lg:flex lg:w-1/2 relative bg-slate-900 overflow-hidden">

        {hasSlides ? (
          slides.map((slide, index) => (
            <div
              key={slide.id}
              className={`absolute inset-0 transition-opacity duration-1000 ease-in-out ${index === currentSlide ? 'opacity-100' : 'opacity-0'}`}
            >
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent z-10"></div>
              <img
                src={slide.image}
                alt={slide.title}
                className="absolute inset-0 w-full h-full object-cover opacity-90"
              />
              <div className="relative z-20 p-16 flex flex-col justify-end h-full text-white">
                <h1 className="text-5xl font-light mb-6 leading-tight" dangerouslySetInnerHTML={{ __html: slide.title.replace(/\n/g, '<br/>') }}></h1>
                <p className="text-lg text-slate-200 mb-8 max-w-md">{slide.subtitle}</p>
                <button className="w-fit px-8 py-3 bg-red-600 text-white font-bold rounded-none hover:bg-red-700 transition-colors uppercase tracking-widest text-sm shadow-lg shadow-red-600/30">
                  Learn More
                </button>
              </div>
            </div>
          ))
        ) : (
          <div className="absolute inset-0 bg-black z-10 flex items-center justify-center">
            <div className="text-white/20 text-lg font-light tracking-widest">NO SLIDES CONFIGURED</div>
          </div>
        )}

        {/* Slider Indicators */}
        {hasSlides && slides.length > 1 && (
          <div className="absolute bottom-8 left-16 z-30 flex gap-2">
            {slides.map((_, index) => (
              <button
                key={index}
                onClick={() => setCurrentSlide(index)}
                className={`h-1.5 rounded-full transition-all ${index === currentSlide ? 'w-8 bg-red-600' : 'w-2 bg-white/50 hover:bg-white/80'}`}
              />
            ))}
          </div>
        )}
      </div>

      {/* Right Side - Form */}
      <div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-16 lg:px-24 py-12 relative">
        {branding?.appLogo ? (
          <div className="bg-black p-4 rounded-2xl mb-12 mx-auto w-fit shadow-lg shadow-red-600/20">
            <img src={branding.appLogo} alt="Logo" className="h-8 w-auto object-contain" />
          </div>
        ) : (
          <div className="flex items-center justify-center gap-3 mb-12">
            <div className="w-10 h-10 bg-black rounded flex items-center justify-center border border-red-600/30">
              <Globe className="text-red-600 w-6 h-6" />
            </div>
            <span className="text-xl font-bold tracking-tight text-white">{branding?.appName || 'CLOUDCORE'}</span>
          </div>
        )}

        {isForgot ? (
          <div className="max-w-md w-full mx-auto">
            <button onClick={() => { setIsForgot(false); setResetStatus('idle'); }} className="mb-6 text-sm text-slate-500 hover:text-red-600 font-medium transition-colors">
              <ArrowLeft size={16} /> Back to Login
            </button>
            <h2 className="text-3xl font-light text-slate-900 mb-2">Reset Password</h2>
            <p className="text-slate-500 mb-8 text-sm">Enter your email to receive reset instructions.</p>

            {resetStatus === 'success' ? (
              <div className="bg-emerald-50 border border-emerald-100 p-6 rounded-lg text-center">
                <CheckCircle2 size={48} className="text-emerald-500 mx-auto mb-4" />
                <h3 className="text-emerald-800 font-bold mb-2">Check your inbox</h3>
                <p className="text-emerald-600 text-sm">We've sent a link to <b>{resetEmail}</b></p>
              </div>
            ) : (
              <form onSubmit={handleResetSubmit} className="space-y-6">
                {error && (
                  <div className="p-4 bg-red-50 text-red-600 text-sm rounded border border-red-100 flex items-center gap-3">
                    <AlertCircle size={18} /> {error}
                  </div>
                )}
                <div className="relative group">
                  <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                    <Mail className="w-5 h-5" />
                  </div>
                  <input
                    type="email"
                    value={resetEmail}
                    onChange={(e) => setResetEmail(e.target.value)}
                    className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all"
                    placeholder="name@company.com"
                    required
                  />
                </div>
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3.5 rounded-none transition-colors duration-200 mt-6 uppercase tracking-widest text-sm shadow-lg shadow-red-600/30"
                >
                  {loading ? 'Sending Link...' : 'Send Reset Link'}
                </button>
              </form>
            )}
          </div>
        ) : (
          <div className="max-w-md w-full mx-auto">
            <h2 className="text-3xl font-light text-slate-900 mb-2">
              {isRegister ? 'Create Account' : `Log in to ${branding?.appName || 'CloudCore'}`}
            </h2>
            <p className="text-slate-500 mb-10 text-sm">
              {isRegister ? 'Please enter your details to proceed.' : 'Please enter your credentials to proceed.'}
            </p>

            {error && (
              <div className="mb-6 p-4 bg-red-50 text-red-600 text-sm rounded border border-red-100 flex items-start gap-3">
                <AlertCircle size={18} className="shrink-0 mt-0.5" />
                <span>{error}</span>
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-6">
              {isRegister ? (
                <div className="space-y-4 max-h-[50vh] overflow-y-auto pr-2 custom-scrollbar">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="relative group">
                      <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                        <User className="w-5 h-5" />
                      </div>
                      <label className="sr-only">First Name</label>
                      <input type="text" name="firstname" value={regData.firstname} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="First Name" />
                    </div>
                    <div className="relative group">
                      <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                        <User className="w-5 h-5" />
                      </div>
                      <label className="sr-only">Last Name</label>
                      <input type="text" name="lastname" value={regData.lastname} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Last Name" />
                    </div>
                  </div>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <Mail className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Email</label>
                    <input type="email" name="email" value={regData.email} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Email Address" />
                  </div>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <Lock className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Password</label>
                    <input type="password" name="password" value={regData.password} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Password" />
                  </div>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <Phone className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Phone</label>
                    <input type="text" name="phonenumber" value={regData.phonenumber} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Phone Number" />
                  </div>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <MapPin className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Address</label>
                    <input type="text" name="address1" value={regData.address1} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Address Line 1" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="relative group">
                      <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                        <MapPin className="w-5 h-5" />
                      </div>
                      <label className="sr-only">City</label>
                      <input type="text" name="city" value={regData.city} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="City" />
                    </div>
                    <div className="relative group">
                      <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                        <MapPin className="w-5 h-5" />
                      </div>
                      <label className="sr-only">Postcode</label>
                      <input type="text" name="postcode" value={regData.postcode} onChange={handleRegChange} required className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all" placeholder="Postcode" />
                    </div>
                  </div>
                </div>
              ) : (
                <>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <Mail className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Email</label>
                    <input
                      type="email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all"
                      placeholder="name@company.com"
                      required
                    />
                  </div>
                  <div className="relative group">
                    <div className="absolute left-4 top-3.5 text-slate-400 group-focus-within:text-red-600 transition-colors">
                      <Lock className="w-5 h-5" />
                    </div>
                    <label className="sr-only">Password</label>
                    <input
                      type="password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="w-full bg-slate-50 border-none focus:ring-2 focus:ring-red-600 rounded-none pl-12 pr-4 py-3.5 text-slate-900 placeholder:text-slate-400 font-medium transition-all"
                      placeholder="••••••••••••"
                      required
                    />
                  </div>
                </>
              )}

              <button
                type="submit"
                disabled={loading}
                className="group relative w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3.5 rounded-none transition-all duration-200 overflow-hidden shadow-lg shadow-red-600/30"
              >
                <div className="absolute inset-0 w-full h-full bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:animate-shimmer"></div>
                <span className="relative flex items-center justify-center gap-2 uppercase tracking-widest text-sm">
                  {loading ? 'Authenticating...' : (isRegister ? 'Register' : 'Log In')}
                  {!loading && <ChevronRight className="w-4 h-4" />}
                </span>
              </button>

              {!isRegister && (
                <div className="space-y-4 pt-2">
                  <div className="pt-6 border-t border-slate-100 flex justify-between items-center text-sm">
                    <button type="button" onClick={() => setIsForgot(true)} className="text-slate-500 hover:text-red-600 font-medium transition-colors underline decoration-slate-300 underline-offset-4 hover:decoration-red-200">
                      Forgot password?
                    </button>
                    <button type="button" onClick={() => setIsRegister(true)} className="text-slate-500 hover:text-red-600 font-medium transition-colors underline decoration-slate-300 underline-offset-4 hover:decoration-red-200">
                      Need an account? Sign Up
                    </button>
                  </div>
                </div>
              )}

              {isRegister && (
                <div className="pt-4 text-center">
                  <button
                    type="button"
                    onClick={() => setIsRegister(false)}
                    className="text-slate-400 hover:text-red-600 transition-colors flex items-center gap-2 mb-8 group"
                  >
                    <div className="p-1 rounded bg-slate-100 group-hover:bg-red-50 transition-colors">
                      <ArrowLeft className="w-4 h-4" />
                    </div>
                    <span className="text-sm font-medium">Back to Login</span>
                  </button>
                </div>
              )}
            </form>
          </div>
        )}
      </div>
    </div>
  );
};

export default LoginView;
