﻿'use client'

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { dashboardApi } from '@/api/dashboardClient';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CountryCodeDropdown } from '@/components/ui/CountryCodeDropdown';
import { X, GraduationCap, BookOpen, Award, CheckCircle, ShieldCheck } from 'lucide-react';
import TurnstileWidget from '@/components/ui/TurnstileWidget';
import { getApiPath, withBasePath } from '@/lib/basePath';

const courses = [
  { id: 'tesol', name: 'Level 5 certTESOL', description: 'Internationally recognized TESOL certification' },
  { id: 'voice-accent', name: 'Voice and Accent Program', description: 'Master pronunciation and accent training' },
  { id: 'ielts', name: 'IELTS Preparation', description: 'Comprehensive IELTS speaking preparation' },
  { id: 'business', name: 'Business English', description: 'Professional English communication skills' },
];

export default function OralDrillLogin({ onClose, onLoginSuccess }) {
  const [isSignUp, setIsSignUp] = useState(true);
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    password: '',
    course: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [countryCode, setCountryCode] = useState('+91');
  const [turnstileToken, setTurnstileToken] = useState('');
  const [turnstileResetKey, setTurnstileResetKey] = useState(0);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      if (isSignUp) {
        if (!turnstileToken) {
          throw new Error('Complete the security verification before creating your account.');
        }
        const response = await fetch(getApiPath('/api/auth/register'), {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            firstName: formData.firstName.trim(),
            lastName: formData.lastName.trim(),
            email: formData.email.trim(),
            password: formData.password,
            countryCode,
            phoneNumber: formData.phone,
            turnstileToken,
          }),
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok) {
          setTurnstileToken('');
          setTurnstileResetKey((value) => value + 1);
          throw new Error(data.message || 'Could not create your account.');
        }
        if (!data.requiresEmailVerification) throw new Error('Email verification could not be started.');

        sessionStorage.setItem('register_otp_email', data.email || formData.email.trim());
        sessionStorage.setItem('oral_drill_preferred_course', formData.course);
        window.location.assign(withBasePath(`/register/verify?email=${encodeURIComponent(data.email || formData.email.trim())}&redirect=${encodeURIComponent('/tools/oral-drill')}`));
        return;
      } else if (dashboardApi?.auth?.loginViaEmailPassword) {
        await dashboardApi.auth.loginViaEmailPassword({
          email: formData.email,
          password: formData.password,
        });
      }

      if (onLoginSuccess) onLoginSuccess();
    } catch (err) {
      setError(err?.message || 'An error occurred. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center p-4 overflow-y-auto"
      style={{
        backgroundImage: 'url("https://images.unsplash.com/photo-1503676260728-1c00da094a0b?w=1920&h=1080&fit=crop")',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
      }}
    >
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
      <motion.div
        initial={{ scale: 0.95, opacity: 0, y: 20 }}
        animate={{ scale: 1, opacity: 1, y: 0 }}
        exit={{ scale: 0.95, opacity: 0, y: 20 }}
        className="w-full max-w-7xl my-4 relative z-10"
      >
        <div className="grid md:grid-cols-5 gap-0 bg-white rounded-2xl shadow-2xl overflow-hidden border-4 border-[#D4A853] max-h-[95vh]">
          <div className="md:col-span-2 bg-[#4A1429] p-8 relative overflow-hidden min-h-[400px] md:min-h-0">
            <div className="absolute inset-0 opacity-5">
              <div
                className="absolute top-0 left-0 w-full h-full"
                style={{
                  backgroundImage: 'url("https://images.unsplash.com/photo-1524178232363-1fb2b075b655?w=800&h=1200&fit=crop")',
                  backgroundSize: 'cover',
                  backgroundPosition: 'center',
                }}
              ></div>
            </div>

            <button
              onClick={onClose}
              className="absolute top-4 right-4 w-10 h-10 bg-white/10 hover:bg-white/20 rounded-lg flex items-center justify-center transition-colors z-10"
            >
              <X className="w-5 h-5 text-white" />
            </button>

            <div className="relative h-full flex flex-col justify-between">
              <div>
                <div className="flex items-center gap-3 mb-8">
                  <div className="w-12 h-12 bg-white rounded-lg flex items-center justify-center">
                    <span className="text-[#4A1429] font-bold">CV</span>
                  </div>
                  <div>
                    <h1 className="text-xl font-bold text-white">Cambridge Veritas</h1>
                    <p className="text-white/80 text-sm">Level 5 TESOL Certification</p>
                  </div>
                </div>

                <h2 className="text-3xl font-bold text-white mb-4">Welcome to Cambridge Veritas!</h2>
                <p className="text-white/90 text-lg mb-8">
                  Join thousands of learners mastering English pronunciation with AI.
                </p>

                <div className="space-y-4 mb-8">
                  {[
                    { icon: GraduationCap, text: 'International TESOL Certification' },
                    { icon: BookOpen, text: 'AI-Powered Pronunciation Practice' },
                    { icon: Award, text: 'Expert Guidance and Support' },
                    { icon: CheckCircle, text: 'Track Your Progress' },
                  ].map((item, i) => (
                    <motion.div
                      key={i}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.1 + i * 0.1 }}
                      className="flex items-center gap-3"
                    >
                      <div className="w-10 h-10 bg-[#D4A853] rounded-lg flex items-center justify-center flex-shrink-0">
                        <item.icon className="w-5 h-5 text-white" />
                      </div>
                      <span className="text-white/95">{item.text}</span>
                    </motion.div>
                  ))}
                </div>
              </div>

              <div className="bg-white/10 backdrop-blur-sm rounded-lg p-4 border border-white/20">
                <div className="flex items-center justify-center gap-1 mb-2">
                  {[...Array(5)].map((_, i) => (
                    <svg key={i} className="w-5 h-5 text-[#D4A853]" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  ))}
                </div>
                <p className="text-sm text-white/80 text-center">5 Star Rating on Verified Google Reviews</p>
              </div>
            </div>
          </div>

          <div className="md:col-span-3 p-6 bg-[#FAF5F0] overflow-y-auto max-h-[95vh]">
            <div className="flex rounded-lg bg-white p-1 mb-4 border-2 border-[#E5DDD5]">
              <button
                onClick={() => setIsSignUp(false)}
                className={`flex-1 py-3 px-6 rounded-md font-semibold transition-all ${
                  !isSignUp
                    ? 'bg-[#4A1429] text-white shadow-md'
                    : 'text-[#4A1429] hover:bg-[#FAF5F0]'
                }`}
              >
                Sign in
              </button>
              <button
                onClick={() => setIsSignUp(true)}
                className={`flex-1 py-3 px-6 rounded-md font-semibold transition-all ${
                  isSignUp
                    ? 'bg-[#4A1429] text-white shadow-md'
                    : 'text-[#4A1429] hover:bg-[#FAF5F0]'
                }`}
              >
                Sign up
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-3">
              {isSignUp && (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-[#4A1429] mb-1">First Name</label>
                      <Input
                        value={formData.firstName}
                        onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                        placeholder="First name"
                        className="h-11 border-2 border-[#E5DDD5] focus:border-[#D4A853] rounded-lg bg-white"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[#4A1429] mb-1">Last Name</label>
                      <Input
                        value={formData.lastName}
                        onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                        placeholder="Last name"
                        className="h-11 border-2 border-[#E5DDD5] focus:border-[#D4A853] rounded-lg bg-white"
                        required
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-[#4A1429] mb-1">Phone</label>
                    <div className="relative flex h-11 rounded-lg border-2 border-[#E5DDD5] bg-white focus-within:border-[#D4A853]">
                      <CountryCodeDropdown value={countryCode} onChange={setCountryCode} fitMenuToField />
                      <Input
                        type="tel"
                        value={formData.phone}
                        onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                        placeholder="Enter your phone"
                        className="min-w-0 flex-1 h-full border-0 focus:border-0 rounded-r-lg bg-white"
                        required
                      />
                    </div>
                  </div>
                </>
              )}

              <div>
                <label className="block text-sm font-medium text-[#4A1429] mb-1">Email</label>
                <Input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                  placeholder="name@example.com"
                  className="h-11 border-2 border-[#E5DDD5] focus:border-[#D4A853] rounded-lg bg-white"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-[#4A1429] mb-1">Password</label>
                <Input
                  type="password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  placeholder="******"
                  className="h-11 border-2 border-[#E5DDD5] focus:border-[#D4A853] rounded-lg bg-white"
                  required
                />
              </div>

              {isSignUp && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-[#4A1429] mb-2">Select Your Course</label>
                    <div className="space-y-2">
                    {courses.map((course) => (
                      <label
                        key={course.id}
                        className={`block p-3 rounded-lg border-2 cursor-pointer transition-all ${
                          formData.course === course.id
                            ? 'border-[#D4A853] bg-white shadow-sm'
                            : 'border-[#E5DDD5] bg-white hover:border-[#D4A853]/50'
                        }`}
                      >
                        <div className="flex items-start gap-3">
                          <input
                            type="radio"
                            name="course"
                            value={course.id}
                            checked={formData.course === course.id}
                            onChange={(e) => setFormData({ ...formData, course: e.target.value })}
                            className="mt-1 w-4 h-4"
                            style={{ accentColor: '#D4A853' }}
                            required
                          />
                          <div className="flex-1">
                            <div className="font-semibold text-[#4A1429]">{course.name}</div>
                            <div className="text-sm text-[#6B5D52]">{course.description}</div>
                          </div>
                        </div>
                      </label>
                    ))}
                    </div>
                  </div>

                  <div className="rounded-xl border-2 border-[#E5DDD5] bg-white p-3">
                    <div className="mb-2 flex items-center gap-2 text-xs font-bold uppercase tracking-wide text-[#6B5D52]">
                      <ShieldCheck className="h-4 w-4 text-[#4A1429]" /> Security verification
                    </div>
                    <TurnstileWidget
                      action="register"
                      resetKey={turnstileResetKey}
                      onVerify={setTurnstileToken}
                      onExpire={() => setTurnstileToken('')}
                      onError={() => setTurnstileToken('')}
                    />
                  </div>
                </>
              )}

              {error && (
                <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
                  {error}
                </div>
              )}

              <Button
                type="submit"
                disabled={loading || (isSignUp && !turnstileToken)}
                className="w-full h-12 bg-[#4A1429] hover:bg-[#3A1020] text-white font-bold rounded-lg shadow-md disabled:opacity-50"
              >
                {loading ? 'Please wait...' : isSignUp ? 'Sign up' : 'Sign in'}
              </Button>
            </form>

            {!isSignUp && (
              <p className="text-center text-sm text-[#6B5D52] mt-4">
                Don&apos;t have an account?{' '}
                <button
                  onClick={() => setIsSignUp(true)}
                  className="text-[#4A1429] font-semibold hover:underline"
                >
                  Sign up
                </button>
              </p>
            )}
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
}
