import React, { useState } from 'react';
import { Lock, Phone, AlertCircle, ArrowLeft, Store } from 'lucide-react';

interface AdminLoginProps {
  onLogin: (success: boolean) => void;
  onClose: () => void;
  isFullScreen?: boolean;
}

const AdminLogin: React.FC<AdminLoginProps> = ({ onLogin, onClose, isFullScreen = false }) => {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPass, setShowPass] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError('');

    const cleanPhone = phone.replace(/[^0-9]/g, '');
    if (cleanPhone.length < 10) {
      setError('সঠিক ফোন নম্বর দিন');
      setIsSubmitting(false);
      return;
    }

    try {
      // ── Tenant Login via /api/auth/login ──────────────────────────────────────────
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: cleanPhone, password }),
      });
      const data = await res.json();

      if (data.success) {
        // Save tenant token & data
        localStorage.setItem('tenant_token', data.token);
        localStorage.setItem('tenant_data', JSON.stringify(data));
        // Set admin session with role='admin' so canAccess() grants full access
        const adminUser = {
          id: parseInt(String(data.id || 0), 10) || 0,
          name: data.name || data.business_name || 'Admin',
          email: data.phone || '',
          role: 'admin',
          permissions: {},
          created_at: data.created_at || new Date().toISOString(),
        };
        sessionStorage.setItem('shophyfast_admin_auth', 'true');
        sessionStorage.setItem('admin_user', JSON.stringify(adminUser));
        onLogin(true);
        return;
      }

      // Login failed
      setError(data.error || 'ফোন নম্বর বা পাসওয়ার্ড ভুল। আবার চেষ্টা করুন।');
    } catch {
      setError('সংযোগ সমস্যা। আবার চেষ্টা করুন।');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className={`flex items-center justify-center p-4 ${isFullScreen ? 'min-h-[80vh]' : 'fixed inset-0 z-[200] bg-black/80 backdrop-blur-md'}`}
      style={{ fontFamily: "'Inter', 'Hind Siliguri', sans-serif" }}>
      <div className="bg-white dark:bg-slate-900 rounded-[32px] w-full max-w-md p-8 shadow-2xl border border-slate-100 dark:border-slate-800">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4" style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 8px 25px rgba(124,58,237,0.35)' }}>
            <Store className="text-white" size={30} />
          </div>
          <h2 className="text-2xl font-black text-slate-900 dark:text-white">Admin Dashboard</h2>
          <p className="text-slate-500 text-sm font-medium mt-1">আপনার Store Account দিয়ে Login করুন</p>
        </div>

        {/* Form */}
        <form onSubmit={handleLogin} className="space-y-5">
          {/* Phone Field */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-black uppercase text-slate-400 ml-1 tracking-widest block">
              ফোন নম্বর / Email
            </label>
            <div className="relative">
              <Phone className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
              <input
                type="text"
                placeholder="01XXXXXXXXX"
                className="w-full pl-12 pr-4 py-4 bg-slate-50 dark:bg-slate-800 border-2 border-transparent rounded-2xl font-bold transition-all outline-none focus:border-purple-500 text-slate-900 dark:text-white"
                value={phone}
                onChange={e => setPhone(e.target.value)}
                required
                disabled={isSubmitting}
                autoComplete="username"
              />
            </div>
          </div>

          {/* Password Field */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-black uppercase text-slate-400 ml-1 tracking-widest block">
              পাসওয়ার্ড
            </label>
            <div className="relative">
              <Lock className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
              <input
                type={showPass ? 'text' : 'password'}
                placeholder="••••••••"
                className="w-full pl-12 pr-12 py-4 bg-slate-50 dark:bg-slate-800 border-2 border-transparent rounded-2xl font-bold transition-all outline-none focus:border-purple-500 text-slate-900 dark:text-white"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
                disabled={isSubmitting}
                autoComplete="current-password"
              />
              <button type="button" onClick={() => setShowPass(!showPass)}
                className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 transition text-xs font-bold">
                {showPass ? '🙈' : '👁️'}
              </button>
            </div>
          </div>

          {/* Error */}
          {error && (
            <div className="flex items-center gap-2 text-red-600 text-sm bg-red-50 dark:bg-red-950/20 p-4 rounded-2xl border border-red-100 font-semibold">
              <AlertCircle size={16} /> {error}
            </div>
          )}

          {/* Submit */}
          <button type="submit" disabled={isSubmitting}
            className="w-full py-4 text-white rounded-2xl font-black text-lg transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
            style={{ background: 'linear-gradient(135deg, #7c3aed, #4f46e5)', boxShadow: '0 8px 25px rgba(124,58,237,0.35)' }}>
            {isSubmitting ? '⏳ Login হচ্ছে...' : '🚀 Login করুন'}
          </button>

          {/* Back */}
          <button type="button" onClick={onClose} disabled={isSubmitting}
            className="w-full py-2 text-slate-400 font-black hover:text-slate-700 dark:hover:text-white transition-colors flex items-center justify-center gap-2 uppercase text-xs tracking-widest disabled:opacity-50">
            <ArrowLeft size={13} /> Back to Website
          </button>
        </form>

        {/* Hint */}
        <div className="mt-6 text-center">
          <p className="text-xs text-slate-400">
            Account নেই?{' '}
            <a href="/" className="text-purple-600 font-black hover:underline">
              shophyfast.com থেকে তৈরি করুন
            </a>
          </p>
        </div>
      </div>
    </div>
  );
};

export default AdminLogin;