import React, { useState } from 'react';
import { Mail, Lock, User, UtensilsCrossed, ArrowRight, ShieldCheck, FileText, MapPin, Phone } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

const Login = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [role, setRole] = useState('user');
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phoneNumber: '',
    password: '',
    gstNo: '',
    restaurantName: '',
    location: '',
  });
  const [certificateImage, setCertificateImage] = useState(null);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleFileChange = (e) => {
    setCertificateImage(e.target.files[0]);
  };

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

    try {
      if (isLogin) {
        const { data } = await axios.post('http://localhost:5000/api/auth/login', {
          email: formData.email,
          password: formData.password,
          role: role
        });
        localStorage.setItem('userInfo', JSON.stringify(data));
        navigate(data.role === 'owner' ? '/owner' : '/');
      } else {
        const data = new FormData();
        data.append('name', formData.name);
        data.append('email', formData.email);
        data.append('phoneNumber', formData.phoneNumber);
        data.append('password', formData.password);
        data.append('role', role);

        if (role === 'owner') {
          data.append('gstNo', formData.gstNo);
          data.append('restaurantName', formData.restaurantName);
          data.append('location', formData.location);
          if (certificateImage) data.append('certificateImage', certificateImage);
          else {
            setError('Certificate image is required for owners');
            return;
          }
        }

        const res = await axios.post('http://localhost:5000/api/auth/register', data);
        localStorage.setItem('userInfo', JSON.stringify(res.data));
        navigate(res.data.role === 'owner' ? '/owner' : '/');
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Authentication failed');
    }
  };

  return (
    <div className="pt-20 min-h-screen bg-gray-50 flex items-center justify-center p-6">
      <div className={`max-w-6xl w-full bg-white rounded-[40px] shadow-2xl flex flex-col md:flex-row overflow-hidden border border-gray-100 transition-all duration-500`}>
        
        {/* Visual Side */}
        <div className="hidden md:flex md:w-2/5 relative bg-secondary p-12 flex-col justify-center text-white text-center">
            <UtensilsCrossed size={70} className="mx-auto mb-8 text-primary" />
            <h2 className="text-4xl font-bold font-outfit mb-4">
                {isLogin ? 'Welcome Back!' : 'Start Your Journey'}
            </h2>
            <p className="text-gray-400 text-lg">
                {isLogin 
                  ? 'Join us again for an exceptional dining experience.' 
                  : (role === 'owner' 
                      ? 'Register your restaurant and start accepting bookings today.' 
                      : 'Create an account to book the best tables in town.')}
            </p>
            <div className="mt-12 pt-12 border-t border-white/10">
                <p className="text-sm text-gray-500 mb-4">{isLogin ? "Don't have an account?" : "Already have an account?"}</p>
                <button 
                  onClick={() => setIsLogin(!isLogin)}
                  className="bg-white/10 hover:bg-white/20 px-8 py-3 rounded-2xl font-bold transition-all"
                >
                  {isLogin ? 'Sign Up' : 'Sign In'}
                </button>
            </div>
        </div>

        {/* Form Side */}
        <div className="w-full md:w-3/5 p-10 lg:p-16 max-h-[90vh] overflow-y-auto">
          <div className="mb-8">
            <h1 className="text-3xl font-bold font-outfit text-secondary mb-2">
              {isLogin ? 'Sign In' : 'Create Account'}
            </h1>
            <div className="flex gap-4 mt-6">
                <button 
                  onClick={() => setRole('user')}
                  className={`flex-1 py-3 rounded-2xl font-bold border-2 transition-all ${role === 'user' ? 'border-primary bg-primary/5 text-primary' : 'border-gray-100 text-gray-400'}`}
                >
                  Customer
                </button>
                <button 
                  onClick={() => setRole('owner')}
                  className={`flex-1 py-3 rounded-2xl font-bold border-2 transition-all ${role === 'owner' ? 'border-primary bg-primary/5 text-primary' : 'border-gray-100 text-gray-400'}`}
                >
                  Restaurant Owner
                </button>
            </div>
          </div>

          {error && <div className="bg-red-50 text-red-500 p-4 rounded-xl mb-6 text-sm font-medium">{error}</div>}

          <form onSubmit={handleSubmit} className="space-y-4">
            {!isLogin && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Full Name</label>
                  <div className="relative">
                    <User className="absolute left-4 top-3 text-gray-400" size={18} />
                    <input 
                      name="name"
                      onChange={handleInputChange}
                      type="text" placeholder="John Doe" 
                      className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Phone Number</label>
                  <div className="relative">
                    <Phone className="absolute left-4 top-3 text-gray-400" size={18} />
                    <input 
                      name="phoneNumber"
                      onChange={handleInputChange}
                      type="tel" placeholder="+91 9876543210" 
                      className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                      required
                    />
                  </div>
                </div>
              </div>
            )}

            <div className="space-y-2">
              <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Email Address</label>
              <div className="relative">
                <Mail className="absolute left-4 top-3 text-gray-400" size={18} />
                <input 
                  name="email"
                  onChange={handleInputChange}
                  type="email" placeholder="name@example.com" 
                  className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                  required
                />
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Password</label>
              <div className="relative">
                <Lock className="absolute left-4 top-3 text-gray-400" size={18} />
                <input 
                  name="password"
                  onChange={handleInputChange}
                  type="password" placeholder="••••••••" 
                  className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                  required
                />
              </div>
            </div>

            {/* Owner Specific Fields */}
            {!isLogin && role === 'owner' && (
              <div className="pt-4 space-y-4 animate-in fade-in slide-in-from-top-2">
                <hr className="border-gray-100" />
                <p className="text-sm font-bold text-secondary flex items-center gap-2">
                    <ShieldCheck size={18} className="text-primary" />
                    Business Verification
                </p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">GST Number</label>
                        <div className="relative">
                            <FileText className="absolute left-4 top-3 text-gray-400" size={18} />
                            <input 
                              name="gstNo"
                              onChange={handleInputChange}
                              type="text" placeholder="22AAAAA0000A1Z5" 
                              className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                              required
                            />
                        </div>
                    </div>
                    <div className="space-y-2">
                        <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Restaurant Name</label>
                        <div className="relative">
                            <UtensilsCrossed className="absolute left-4 top-3 text-gray-400" size={18} />
                            <input 
                              name="restaurantName"
                              onChange={handleInputChange}
                              type="text" placeholder="The Grand Palace" 
                              className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                              required
                            />
                        </div>
                    </div>
                </div>
                <div className="space-y-2">
                    <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Location</label>
                    <div className="relative">
                        <MapPin className="absolute left-4 top-3 text-gray-400" size={18} />
                        <input 
                          name="location"
                          onChange={handleInputChange}
                          type="text" placeholder="Main St, City Center" 
                          className="w-full bg-gray-50 border border-gray-100 rounded-2xl py-3 pl-12 pr-4 outline-none focus:border-primary transition-all"
                          required
                        />
                    </div>
                </div>
                <div className="space-y-2">
                    <label className="text-xs font-bold text-gray-400 uppercase tracking-wider ml-1">Upload Certificate (Image)</label>
                    <input 
                      type="file" 
                      onChange={handleFileChange}
                      accept="image/*"
                      className="w-full bg-gray-50 border border-dashed border-gray-300 rounded-2xl py-4 px-6 text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-bold file:bg-primary/10 file:text-primary hover:file:bg-primary/20 cursor-pointer"
                      required={!isLogin && role === 'owner'}
                    />
                </div>
              </div>
            )}

            <button 
              type="submit"
              className="w-full bg-primary text-white py-4 rounded-2xl font-bold shadow-xl shadow-primary/20 hover:bg-primary-dark transition-all flex items-center justify-center gap-2 mt-6"
            >
              {isLogin ? 'Sign In' : 'Complete Registration'}
              <ArrowRight size={18} />
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;
