import { useState, useEffect } from 'react';
import { EyeOutlined, EyeInvisibleOutlined, UserOutlined, LockOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { addUser } from '../../redux/rtk/features/user/userSlice';
import { loadPermissionById } from '../../redux/rtk/features/auth/authSlice';
import { getSetting } from '../../redux/rtk/features/setting/settingSlice';
import LoginTable from '../Card/LoginTable';

export default function Login() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  });
  const [loading, setLoading] = useState(false);
  const [defaultValue, setDefaultValue] = useState('');
  const { data, loading: settingLoading } = useSelector((state) => state?.setting) || {};
  const [imageError, setImageError] = useState(false);
  const loginTable = import.meta.env.VITE_LOGIN_TABLE;

  // Check if user is already logged in
  const isLogged = Boolean(localStorage.getItem('isLogged'));
  useEffect(() => {
    if (isLogged) {
      navigate('/admin');
    }
  }, [isLogged, navigate]);

  // Set default values from LoginTable
  useEffect(() => {
    if (defaultValue && defaultValue[0]) {
      setFormData({
        username: defaultValue[0].username || '',
        password: defaultValue[0].password || ''
      });
    }
  }, [defaultValue]);

  const handleSubmit = async () => {
    if (!formData.username || !formData.password) {
      return;
    }
    
    setLoading(true);
    const resp = await dispatch(addUser(formData));
    if (resp.payload.message === 'success') {
      setLoading(false);
      dispatch(getSetting());
      dispatch(loadPermissionById(resp.payload?.data?.roleId));
    } else {
      setLoading(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleSubmit();
    }
  };

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

  const transactions = [
    { id: 'TXN-001', app: 'Apple M1 Pro 14"', date: '12 Jan, 2025', amount: '$2,849', status: 'Paid' },
    { id: 'TXN-002', app: 'Sony WH-1000', date: '11 Jan, 2025', amount: '$349', status: 'Pending' },
    { id: 'TXN-003', app: 'Magic Keyboard', date: '10 Jan, 2025', amount: '$299', status: 'Paid' }
  ];

  return (
    <div className="min-h-screen flex flex-col lg:flex-row">
      {/* Left Side - Modern Dashboard Preview */}
      <div className="hidden lg:flex w-full lg:w-1/2 bg-gradient-to-br from-indigo-600 via-blue-600 to-indigo-700 items-center justify-center p-4 xl:p-8 relative overflow-hidden">
        {/* Modern Square Grid Pattern Background */}
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-0 left-0 w-full h-full" style={{
            backgroundImage: `
              linear-gradient(to right, rgba(255,255,255,0.2) 2px, transparent 1px),
              linear-gradient(to bottom, rgba(255,255,255,0.2) 2px, transparent 1px)
            `,
            backgroundSize: '60px 60px'
          }}></div>
          {/* Accent squares for ERP modules concept */}
          <div className="absolute top-20 left-20 w-24 h-24 border-2 border-white/20 rounded-lg"></div>
          <div className="absolute top-40 right-32 w-16 h-16 border-2 border-white/20 rounded-lg rotate-12"></div>
          <div className="absolute bottom-32 left-40 w-20 h-20 border-2 border-white/20 rounded-lg -rotate-6"></div>
          <div className="absolute bottom-20 right-20 w-28 h-28 border-2 border-white/20 rounded-lg rotate-6"></div>
        </div>

        {/* Half Circle Decorative Shapes - Top Left */}
        <div className="absolute -top-32 -left-32 w-64 h-64 bg-white/5 rounded-full border-none border-white/20"></div>
        
        {/* Half Circle Decorative Shapes - Bottom Right */}
        <div className="absolute -bottom-32 -right-32 w-64 h-64 bg-white/5 rounded-full border-none border-white/20"></div>

        {/* ERP Module Connection Lines */}
        <svg className="absolute inset-0 w-full h-full opacity-20" style={{pointerEvents: 'none'}}>
          <line x1="20%" y1="20%" x2="80%" y2="80%" stroke="white" strokeWidth="1" strokeDasharray="5,5"/>
          <line x1="80%" y1="20%" x2="20%" y2="80%" stroke="white" strokeWidth="1" strokeDasharray="5,5"/>
          <circle cx="20%" cy="20%" r="8" fill="white" opacity="0.5"/>
          <circle cx="80%" cy="20%" r="8" fill="white" opacity="0.5"/>
          <circle cx="20%" cy="80%" r="8" fill="white" opacity="0.5"/>
          <circle cx="80%" cy="80%" r="8" fill="white" opacity="0.5"/>
          <circle cx="50%" cy="50%" r="12" fill="white" opacity="0.7"/>
        </svg>

        {/* Gradient Orbs - Smaller for laptop screens */}
        <div className="absolute top-10 right-10 w-64 h-64 xl:w-96 xl:h-96 bg-purple-400 rounded-full blur-3xl opacity-20"></div>
        <div className="absolute bottom-10 left-10 w-56 h-56 xl:w-80 xl:h-80 bg-blue-300 rounded-full blur-3xl opacity-20"></div>

        {/* Content - Optimized for 14" laptops */}
        <div className="relative z-10 w-full max-w-xl xl:max-w-2xl scale-90 xl:scale-100 px-8 lg:px-4">

          {/* Dashboard Preview Card */}
          <div className="bg-white rounded-2xl shadow-2xl p-4 xl:p-6 transform hover:scale-105 transition-transform duration-300">
            {/* Dashboard Header - Stats Grid */}
            <div className="grid grid-cols-2 gap-3 xl:gap-5 mb-3 xl:mb-5">
              {/* Total Sales Card */}
              <div className="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl p-3 xl:p-5 text-white">
                <div className="flex justify-between items-start mb-2 xl:mb-3">
                  <div>
                    <p className="text-xs opacity-90 mb-1">Total Sales</p>
                    <p className="text-lg xl:text-2xl font-bold">$189,374</p>
                  </div>
                  <div className="bg-white/20 rounded-lg px-2 py-0.5 xl:py-1">
                    <span className="text-xs font-medium">+23.5%</span>
                  </div>
                </div>
                <div className="flex items-center text-xs">
                  <span className="opacity-90">↑ 12.5% from last month</span>
                </div>
              </div>

              {/* Active Sessions Card */}
              <div className="bg-white border-2 border-gray-200 rounded-xl p-3 xl:p-5">
                <p className="text-xs text-gray-600 mb-1">Active Sessions</p>
                <p className="text-lg xl:text-2xl font-bold text-gray-800 mb-2">00:01:30</p>
                <div className="h-10 xl:h-14 flex items-end justify-between gap-0.5">
                  {[40, 65, 45, 80, 60, 90, 75, 85, 70, 95, 80, 88].map((height, i) => (
                    <div key={i} className="flex-1 bg-gradient-to-t from-indigo-400 to-indigo-300 rounded-t" style={{height: `${height}%`}}></div>
                  ))}
                </div>
              </div>
            </div>

            {/* Recent Transactions Table */}
            <div className="bg-white rounded-xl border border-gray-100 overflow-hidden">
              {/* Table Header */}
              <div className="bg-gradient-to-r from-gray-50 to-white px-3 xl:px-4 py-2 border-b border-gray-100">
                <div className="flex justify-between items-center">
                  <h3 className="text-xs xl:text-sm font-semibold text-gray-800">Recent Transactions</h3>
                  <button className="text-xs text-indigo-600 font-medium hover:text-indigo-700">View All</button>
                </div>
              </div>

              {/* Table Content */}
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="bg-gray-50 border-b border-gray-100">
                      <th className="px-2 xl:px-4 py-1.5 xl:py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Transaction
                      </th>
                      <th className="px-2 xl:px-4 py-1.5 xl:py-2 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Date
                      </th>
                      <th className="px-2 xl:px-4 py-1.5 xl:py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Amount
                      </th>
                      <th className="px-2 xl:px-4 py-1.5 xl:py-2 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider">
                        Status
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-100">
                    {transactions.map((transaction, i) => (
                      <tr key={i} className="hover:bg-gray-50 transition-colors">
                        <td className="px-2 xl:px-4 py-2 xl:py-2.5 whitespace-nowrap">
                          <div className="flex items-center">
                            <div className="w-7 h-7 xl:w-8 xl:h-8 bg-gradient-to-br from-blue-50 to-indigo-50 rounded-lg flex items-center justify-center mr-2 flex-shrink-0">
                              <span className="text-blue-600 font-semibold text-xs">
                                {transaction.id.split('-')[1]}
                              </span>
                            </div>
                            <div className="min-w-0">
                              <div className="text-xs font-semibold text-gray-900 truncate">{transaction.app}</div>
                            </div>
                          </div>
                        </td>
                        <td className="px-2 xl:px-4 py-2 xl:py-2.5 whitespace-nowrap">
                          <div className="text-xs text-gray-900 font-medium">{transaction.date}</div>
                        </td>
                        <td className="px-2 xl:px-4 py-2 xl:py-2.5 whitespace-nowrap text-right">
                          <div className="text-xs font-bold text-gray-900">{transaction.amount}</div>
                        </td>
                        <td className="px-2 xl:px-4 py-2 xl:py-2.5 whitespace-nowrap text-center">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold border ${
                            transaction.status === 'Paid' 
                              ? 'bg-emerald-50 text-emerald-700 border-emerald-200' 
                              : 'bg-amber-50 text-amber-700 border-amber-200'
                          }`}>
                            {transaction.status}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Table Footer */}
              <div className="px-2 xl:px-3 py-2 border-t border-gray-100 bg-gray-50 flex justify-between items-center text-xs">
                <div className="text-gray-600">
                  Showing <span className="font-semibold text-gray-900">3</span> transactions
                </div>
                <div className="flex gap-1">
                  <button className="px-2 py-1 border border-gray-300 rounded-lg text-xs font-medium text-gray-700 hover:bg-white transition-colors">
                    Prev
                  </button>
                  <button className="px-2 py-1 bg-blue-600 text-white rounded-lg text-xs font-medium hover:bg-blue-700 transition-colors">
                    Next
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Sales Overview Donut - Fixed positioning for laptop screens */}
          <div className="bg-white border-2 border-gray-200 rounded-xl p-3 xl:p-5 absolute -top-12 lg:-top-14 xl:-top-20 right-0 lg:-right-8 xl:-right-[20px] w-28 lg:w-32 xl:w-44 shadow-lg">
            <p className="text-xs text-gray-600 mb-2">Sales Overview</p>
            <div className="relative w-16 h-16 lg:w-20 lg:h-20 xl:w-28 xl:h-28 mx-auto">
              <svg viewBox="0 0 100 100" className="transform -rotate-90">
                <circle cx="50" cy="50" r="40" fill="none" stroke="#e5e7eb" strokeWidth="12"/>
                <circle cx="50" cy="50" r="40" fill="none" stroke="#6366f1" strokeWidth="12" strokeDasharray="188.4" strokeDashoffset="47.1" strokeLinecap="round"/>
              </svg>
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <p className="text-base lg:text-lg xl:text-xl font-bold text-gray-800">6,248</p>
                  <p className="text-xs text-gray-500">Units</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Right Side - Login Form */}
      <div className="w-full lg:w-1/2 bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center p-4 sm:p-6 lg:p-8 min-h-screen lg:min-h-0">
        <div className="w-full max-w-md">
          
          {/* Logo Section */}
          <div className="mb-6 sm:mb-8">
            {data && !settingLoading && (
              <div className="w-[180px] h-[70px] mx-auto flex items-center justify-center mb-4">
                {data?.logo && !imageError ? (
                  <img
                    className="text-white text-center"
                    alt="logo"
                    src={data.logo}
                    style={{ width: '180px', height: '70px' }}
                    onError={() => setImageError(true)}
                  />
                ) : (
                  <h2 className="text-center flex items-center justify-center gap-2 text-3xl">
                    OS
                    <strong className="text-blue-600 font-bold">Inventory</strong>
                  </h2>
                )}
              </div>
            )}
            
            {settingLoading && (
              <div className="w-[180px] h-[70px] mx-auto flex flex-col gap-1 mb-4">
                <div className="bg-slate-200 h-4 rounded w-full animate-pulse"></div>
                <div className="bg-slate-200 h-4 rounded w-full animate-pulse"></div>
                <div className="bg-slate-200 h-4 rounded w-full animate-pulse"></div>
              </div>
            )}
          </div>

          {/* Welcome Text */}
          <div className="mb-6 sm:mb-8">
            <h2 className="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-800 mb-2 text-center">Welcome Back</h2>
            <p className="text-sm sm:text-base text-gray-600 text-center">Sign in to manage your business</p>
          </div>

          {/* Login Form */}
          <div className="space-y-4 sm:space-y-5">
            {/* Username Input */}
            <div>
              <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">
                Username or Email
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 sm:pl-4 flex items-center pointer-events-none">
                  <UserOutlined className="text-gray-400 text-sm sm:text-base" />
                </div>
                <input
                  type="text"
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  onKeyPress={handleKeyPress}
                  placeholder="Enter your username"
                  className="w-full pl-9 sm:pl-11 pr-3 sm:pr-4 py-2.5 sm:py-3 text-sm sm:text-base border border-gray-300 rounded-lg sm:rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                  required
                />
              </div>
            </div>

            {/* Password Input */}
            <div>
              <label className="block text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">
                Password
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 sm:pl-4 flex items-center pointer-events-none">
                  <LockOutlined className="text-gray-400 text-sm sm:text-base" />
                </div>
                <input
                  type={showPassword ? "text" : "password"}
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  onKeyPress={handleKeyPress}
                  placeholder="Enter your password"
                  className="w-full pl-9 sm:pl-11 pr-10 sm:pr-12 py-2.5 sm:py-3 text-sm sm:text-base border border-gray-300 rounded-lg sm:rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-0 pr-3 sm:pr-4 flex items-center text-gray-400 hover:text-gray-600"
                >
                  {showPassword ? <EyeInvisibleOutlined className="text-sm sm:text-base" /> : <EyeOutlined className="text-sm sm:text-base" />}
                </button>
              </div>
            </div>

            {/* Submit Button */}
            <button
              onClick={handleSubmit}
              disabled={loading}
              className="w-full bg-gradient-to-r  from-blue-600 to-blue-600 hover:from-blue-700 hover:to-blue-700 text-white py-2.5 sm:py-3 text-sm sm:text-base rounded-lg sm:rounded-xl font-semibold focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? 'Signing in...' : 'Login'}
            </button>

            {/* Login Table for Demo Accounts */}
            {loginTable === "true" && (
              <div className="py-4">
                <LoginTable setDefaultValue={setDefaultValue} />
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}