import React, { useState, useEffect } from 'react';
import { Search, Home, Briefcase, MessageSquare, User, Star, MapPin, Award, Eye, EyeOff, Mail, Lock, Phone, Loader, AlertCircle } from 'lucide-react';
import { initializeApp } from "firebase/app";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, sendPasswordResetEmail } from "firebase/auth";

// ===== تهيئة Firebase =====
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export default function AjitkhdmApp() {
  const [user, setUser] = useState(null);
  const [showLogin, setShowLogin] = useState(true);
  const [showPw, setShowPw] = useState(false);
  const [tab, setTab] = useState('home');
  const [cat, setCat] = useState('all');
  const [form, setForm] = useState({ name: '', email: '', phone: '', password: '', role: 'worker' });
  const [err, setErr] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const saved = localStorage.getItem('session');
    if (saved) setUser(JSON.parse(saved));
  }, []);

  // ===== تسجيل الدخول =====
  const handleLogin = async () => {
    setErr('');
    setLoading(true);
    try {
      if (!form.email || !form.password) throw new Error('املأ الحقول');
      const result = await signInWithEmailAndPassword(auth, form.email, form.password);
      setUser({ uid: result.user.uid, email: result.user.email });
      localStorage.setItem('session', JSON.stringify({ uid: result.user.uid, email: result.user.email }));
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  };

  // ===== إنشاء حساب =====
  const handleRegister = async () => {
    setErr('');
    setLoading(true);
    try {
      if (!form.name || !form.email || !form.phone || !form.password) throw new Error('املأ كل الحقول');
      if (form.password.length < 6) throw new Error('الباسورد 6 أحرف على الأقل');
      const result = await createUserWithEmailAndPassword(auth, form.email, form.password);
      setUser({ uid: result.user.uid, email: result.user.email });
      localStorage.setItem('session', JSON.stringify({ uid: result.user.uid, email: result.user.email }));
      // تخزين معلومات إضافية محلياً (اختياري)
      localStorage.setItem(`user_${result.user.uid}`, JSON.stringify({ name: form.name, phone: form.phone, role: form.role }));
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  };

  // ===== قائمة العمال والتخصصات =====
  const workers = [
    { id: 1, name: 'أحمد محمد', job: 'معلم بناء', rating: 4.9, reviews: 127, price: '250 درهم/يوم', premium: true, icon: '👷‍♂️', cat: 'construction' },
    { id: 2, name: 'فاطمة أحمد', job: 'مصممة', rating: 4.8, reviews: 89, price: '300 درهم', premium: true, icon: '👩‍💼', cat: 'office' },
    { id: 3, name: 'يوسف خالد', job: 'كهربائي', rating: 4.7, reviews: 56, price: '150 درهم/س', premium: false, icon: '⚡', cat: 'electrical' },
    { id: 4, name: 'سعيد الحسني', job: 'صباغ', rating: 5.0, reviews: 43, price: '200 درهم/يوم', premium: true, icon: '🎨', cat: 'painting' }
  ];

  const cats = [
    { id: 'all', name: 'الكل', icon: '🏢' },
    { id: 'construction', name: 'بناء', icon: '🏗️' },
    { id: 'electrical', name: 'كهرباء', icon: '⚡' },
    { id: 'plumbing', name: 'سباكة', icon: '🔧' },
    { id: 'painting', name: 'صباغة', icon: '🎨' },
    { id: 'office', name: 'مكتبي', icon: '💼' }
  ];

  const filtered = cat === 'all' ? workers : workers.filter(w => w.cat === cat);

  // ===== واجهة تسجيل الدخول / إنشاء حساب =====
  if (!user) {
    return (
      <div className="min-h-screen bg-white" dir="rtl">
        <div className="bg-blue-600 p-6 text-center">
          <h1 className="text-4xl font-bold text-white mb-2">AJITKHDM</h1>
          <p className="text-blue-100 text-sm">أجي تخدم 🇲🇦</p>
        </div>
        <div className="p-6 max-w-md mx-auto">
          {err && (
            <div className="mb-4 p-4 bg-red-50 rounded-lg flex gap-3">
              <AlertCircle className="text-red-600" size={20} />
              <p className="text-red-800 text-sm">{err}</p>
            </div>
          )}
          {showLogin ? (
            <div className="space-y-4">
              <h2 className="text-2xl font-bold text-center mb-6">تسجيل الدخول</h2>
              <div className="relative">
                <Mail className="absolute right-4 top-3.5 text-gray-400" size={20} />
                <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })}
                  placeholder="البريد" className="w-full pr-12 pl-4 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
              </div>
              <div className="relative">
                <Lock className="absolute right-4 top-3.5 text-gray-400" size={20} />
                <input type={showPw ? "text" : "password"} value={form.password}
                  onChange={e => setForm({ ...form, password: e.target.value })} placeholder="الباسورد"
                  className="w-full pr-12 pl-12 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
                <button onClick={() => setShowPw(!showPw)} className="absolute left-4 top-3.5 text-gray-400">
                  {showPw ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>

              {/* زر نسيت كلمة السر الحقيقي */}
              <button
                onClick={async () => {
                  if (!form.email) return alert("دخل البريد ديالك باش تبدل الباسورد");
                  try {
                    await sendPasswordResetEmail(auth, form.email);
                    alert(`تم إرسال رابط إعادة تعيين كلمة السر إلى ${form.email}`);
                  } catch (error) {
                    alert(`حدث خطأ: ${error.message}`);
                  }
                }}
                className="text-sm text-blue-600 hover:underline mt-2"
              >
                نسيت كلمة السر؟
              </button>

              <button onClick={handleLogin} disabled={loading}
                className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2">
                {loading ? <><Loader className="animate-spin" size={20} />جاري...</> : 'دخول'}
              </button>
              <div className="text-center my-4 text-gray-500">أو</div>
              <button onClick={() => setShowLogin(false)} className="w-full border-2 border-blue-600 text-blue-600 py-3 rounded-lg font-bold">
                حساب جديد
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              <h2 className="text-2xl font-bold text-center mb-6">إنشاء حساب</h2>
              <input type="text" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })}
                placeholder="الاسم" className="w-full px-4 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
              <div className="relative">
                <Phone className="absolute right-4 top-3.5 text-gray-400" size={20} />
                <input type="tel" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })}
                  placeholder="الهاتف" className="w-full pr-12 px-4 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
              </div>
              <div className="relative">
                <Mail className="absolute right-4 top-3.5 text-gray-400" size={20} />
                <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })}
                  placeholder="البريد" className="w-full pr-12 px-4 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
              </div>
              <div className="relative">
                <Lock className="absolute right-4 top-3.5 text-gray-400" size={20} />
                <input type={showPw ? "text" : "password"} value={form.password}
                  onChange={e => setForm({ ...form, password: e.target.value })} placeholder="الباسورد (6 أحرف)"
                  className="w-full pr-12 pl-12 py-3 border-2 rounded-lg focus:border-blue-600 outline-none" />
                <button onClick={() => setShowPw(!showPw)} className="absolute left-4 top-3.5 text-gray-400">
                  {showPw ? <EyeOff size={20} /> : <Eye size={20} />}
                </button>
              </div>
              <div>
                <label className="text-sm font-bold mb-2 block">نوع الحساب:</label>
                <div className="flex gap-3">
                  <button onClick={() => setForm({ ...form, role: 'worker' })}
                    className={`flex-1 py-2 border-2 rounded-lg font-bold ${form.role === 'worker' ? 'border-blue-600 bg-blue-50 text-blue-600' : 'border-gray-300'}`}>
                    أبحث عن عمل
                  </button>
                  <button onClick={() => setForm({ ...form, role: 'employer' })}
                    className={`flex-1 py-2 border-2 rounded-lg font-bold ${form.role === 'employer' ? 'border-blue-600 bg-blue-50 text-blue-600' : 'border-gray-300'}`}>
                    أبحث عن عامل
                  </button>
                </div>
              </div>
              <button onClick={handleRegister} disabled={loading}
                className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-2">
                {loading ? <><Loader className="animate-spin" size={20} />جاري...</> : 'إنشاء'}
              </button>
              <button onClick={() => setShowLogin(true)} className="w-full text-blue-600 text-sm hover:underline">
                عندك حساب؟ دخول
              </button>
            </div>
          )}
        </div>
      </div>
    );
  }

  // ===== واجهة المستخدم بعد تسجيل الدخول =====
  return (
    <div className="max-w-md mx-auto bg-gray-50 min-h-screen" dir="rtl">
      <div className="bg-blue-600 p-4 sticky top-0 z-10">
        <h1 className="text-xl font-bold text-white">AJITKHDM</h1>
      </div>
      <div className="pb-20">
        {tab === 'home' && (
          <div className="p-4 space-y-6">
            <div className="bg-blue-600 rounded-2xl p-6 text-white">
              <h1 className="text-2xl font-bold mb-2">مرحباً في أجي تخدم</h1>
              <p className="text-blue-100 mb-4">لقا الصانع المثالي</p>
              <div className="bg-white rounded-lg p-3 flex items-center">
                <Search className="text-gray-400 ml-2" size={20} />
                <input type="text" placeholder="ابحث..." className="flex-1 outline-none text-gray-800" />
              </div>
            </div>
            <div>
              <h2 className="font-bold mb-3">التخصصات</h2>
              <div className="flex gap-2 overflow-x-auto pb-2">
                {cats.map(c => (
                  <button key={c.id} onClick={() => setCat(c.id)}
                    className={`flex-shrink-0 px-4 py-2 rounded-full flex gap-2 ${cat === c.id ? 'bg-blue-600 text-white' : 'bg-white border'}`}>
                    <span>{c.icon}</span><span className="text-sm font-medium">{c.name}</span>
                  </button>
                ))}
              </div>
            </div>
            <div className="space-y-3">
              {filtered.map(w => (
                <div key={w.id} className="bg-white rounded-xl p-4 shadow">
                  <div className="flex gap-3">
                    <div className="text-4xl">{w.icon}</div>
                    <div className="flex-1">
                      <div className="flex gap-2 mb-1">
                        <h3 className="font-bold">{w.name}</h3>
                        {w.premium && (
                          <span className="bg-blue-100 text-blue-700 text-xs px-2 py-1 rounded-full flex items-center gap-1">
                            <Award size={12} />Pro
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-gray-600">{w.job}</p>
                      <div className="flex gap-3 mt-2 text-sm">
                        <div className="flex gap-1">
                          <Star className="text-yellow-500 fill-yellow-500" size={16} />
                          <span className="font-bold">{w.rating}</span>
                          <span className="text-gray-500">({w.reviews})</span>
                        </div>
                      </div>
                      <div className="flex justify-between mt-3">
                        <span className="text-blue-600 font-bold">{w.price}</span>
                        <button className="px-4 py-1.5 bg-blue-600 text-white rounded-lg text-sm">تواصل</button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
        {tab === 'profile' && (
          <div className="p-4">
            <div className="bg-white rounded-2xl p-6 text-center">
              <div className="text-6xl mb-4">👤</div>
              <h2 className="text-xl font-bold">{user.email}</h2>
              <button onClick={() => {
                setUser(null);
                localStorage.removeItem('session');
              }} className="mt-4 w-full bg-red-50 text-red-600 py-3 rounded-lg font-bold">خروج</button>
            </div>
          </div>
        )}
      </div>
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t max-w-md mx-auto">
        <div className="flex justify-around p-3">
          {[
            { id: 'home', icon: Home, name: 'الرئيسية' },
            { id: 'jobs', icon: Briefcase, name: 'وظائف' },
            { id: 'messages', icon: MessageSquare, name: 'رسائل' },
            { id: 'profile', icon: User, name: 'حسابي' }
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`flex flex-col items-center gap-1 ${tab === t.id ? 'text-blue-600' : 'text-gray-400'}`}>
              <t.icon size={24} /><span className="text-xs">{t.name}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Comments