'use client';

import React, { useState, useEffect } from 'react';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/context/ToastContext';
import { profileService, UserProfile, ActivitySummary } from '@/services/profileService';
import { Container } from '@/components/ui/container';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { User, Mail, Phone, Lock, Shield, Activity, AlertTriangle } from 'lucide-react';
import { useRouter } from 'next/navigation';

export default function ProfilePage() {
  const { user: authUser, isAuthenticated, isLoading: authLoading, updateUser, logout } = useAuth();
  const { showToast } = useToast();
  const router = useRouter();

  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [activity, setActivity] = useState<ActivitySummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);

  // Form states
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');

  // Password change states
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordStrength, setPasswordStrength] = useState({ score: 0, message: '' });

  // Delete account states
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deletePassword, setDeletePassword] = useState('');
  const [deleteConfirmation, setDeleteConfirmation] = useState('');

  const loadProfileData = async () => {
    try {
      setLoading(true);
      const [profileData, activityData] = await Promise.all([
        profileService.getProfile(),
        profileService.getActivitySummary(),
      ]);

      setProfile(profileData);
      setActivity(activityData);
      
      // Populate form fields
      setName(profileData.name);
      setEmail(profileData.email);
      setPhone(profileData.phone || '');
    } catch (error) {
      console.error('Failed to load profile:', error);
      const err = error as { response?: { status?: number } };
      
      // If unauthorized, redirect to login
      if (err?.response?.status === 401) {
        showToast({ title: 'يرجى تسجيل الدخول مرة أخرى', type: 'error' });
        router.push('/login');
        return;
      }
      
      showToast({ title: 'فشل تحميل البيانات', type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    console.log('Profile Page - Auth Check:', {
      authLoading,
      isAuthenticated,
      hasUser: !!authUser,
      hasToken: !!authUser,
    });

    // Wait for auth to initialize
    if (authLoading) {
      console.log('Auth still loading, waiting...');
      return;
    }

    if (!isAuthenticated) {
      console.log('Not authenticated, redirecting to login');
      router.push('/login');
      return;
    }

    console.log('Authenticated, loading profile data');
    loadProfileData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated, authLoading, router]);

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Client-side validation
    if (!name.trim()) {
      showToast({ title: 'الاسم مطلوب', type: 'error' });
      return;
    }

    if (name.length < 2 || name.length > 255) {
      showToast({ title: 'الاسم يجب أن يكون بين 2 و 255 حرف', type: 'error' });
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showToast({ title: 'البريد الإلكتروني غير صحيح', type: 'error' });
      return;
    }

    // Phone validation (if provided)
    if (phone && !/^[0-9+\-\s()]+$/.test(phone)) {
      showToast({ title: 'رقم الهاتف غير صحيح', type: 'error' });
      return;
    }

    try {
      setUpdating(true);

      const updatedProfile = await profileService.updateProfile({
        name: name.trim(),
        email: email.trim().toLowerCase(),
        phone: phone.trim() || undefined,
      });

      setProfile(updatedProfile);
      updateUser({
        ...authUser!,
        name: updatedProfile.name,
        email: updatedProfile.email,
        phone: updatedProfile.phone,
      });

      showToast({ title: 'تم تحديث الملف الشخصي بنجاح', type: 'success' });
    } catch (error: unknown) {
      console.error('Profile update failed:', error);
      const err = error as { response?: { data?: { message?: string } }; message?: string };
      const message = err?.response?.data?.message || err?.message || 'فشل تحديث الملف الشخصي';
      showToast({ title: message, type: 'error' });
    } finally {
      setUpdating(false);
    }
  };

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validation
    if (!currentPassword) {
      showToast({ title: 'أدخل كلمة المرور الحالية', type: 'error' });
      return;
    }

    if (!newPassword || newPassword.length < 8) {
      showToast({ title: 'كلمة المرور الجديدة يجب أن تكون 8 أحرف على الأقل', type: 'error' });
      return;
    }

    if (newPassword !== confirmPassword) {
      showToast({ title: 'كلمات المرور غير متطابقة', type: 'error' });
      return;
    }

    if (newPassword === currentPassword) {
      showToast({ title: 'كلمة المرور الجديدة يجب أن تكون مختلفة', type: 'error' });
      return;
    }

    // Check password strength
    const strength = profileService.validatePasswordStrength(newPassword);
    if (!strength.isValid) {
      showToast({ title: strength.message, type: 'error' });
      return;
    }

    try {
      setUpdating(true);

      await profileService.updateProfile({
        current_password: currentPassword,
        password: newPassword,
        password_confirmation: confirmPassword,
      });

      // Clear password fields
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      setPasswordStrength({ score: 0, message: '' });

      showToast({ title: 'تم تغيير كلمة المرور بنجاح', type: 'success' });
    } catch (error: unknown) {
      console.error('Password change failed:', error);
      const err = error as { response?: { data?: { message?: string } }; message?: string };
      const message = err?.response?.data?.message || err?.message || 'فشل تغيير كلمة المرور';
      showToast({ title: message, type: 'error' });
    } finally {
      setUpdating(false);
    }
  };

  const handleDeleteAccount = async () => {
    if (!deletePassword) {
      showToast({ title: 'أدخل كلمة المرور', type: 'error' });
      return;
    }

    if (deleteConfirmation !== 'DELETE') {
      showToast({ title: 'اكتب DELETE للتأكيد', type: 'error' });
      return;
    }

    try {
      setUpdating(true);
      await profileService.deleteAccount(deletePassword);
      
      showToast({ title: 'تم حذف الحساب بنجاح', type: 'success' });
      
      // Logout and redirect
      await logout();
      router.push('/');
    } catch (error: unknown) {
      console.error('Account deletion failed:', error);
      const err = error as { response?: { data?: { message?: string } }; message?: string };
      const message = err?.response?.data?.message || err?.message || 'فشل حذف الحساب';
      showToast({ title: message, type: 'error' });
    } finally {
      setUpdating(false);
    }
  };

  const handlePasswordInput = (value: string) => {
    setNewPassword(value);
    if (value.length > 0) {
      const strength = profileService.validatePasswordStrength(value);
      setPasswordStrength(strength);
    } else {
      setPasswordStrength({ score: 0, message: '' });
    }
  };

  if (loading) {
    return (
      <Container className="py-12">
        <div className="max-w-4xl mx-auto">
          <div className="animate-pulse space-y-4">
            <div className="h-8 bg-gray-200 rounded w-1/4"></div>
            <div className="h-64 bg-gray-200 rounded"></div>
            <div className="h-64 bg-gray-200 rounded"></div>
          </div>
        </div>
      </Container>
    );
  }

  if (!profile) {
    return (
      <Container className="py-12">
        <div className="text-center">
          <p className="text-gray-600">فشل تحميل الملف الشخصي</p>
          <Button onClick={loadProfileData} className="mt-4">
            إعادة المحاولة
          </Button>
        </div>
      </Container>
    );
  }

  return (
    <Container className="py-8 md:py-12">
      <div className="max-w-4xl mx-auto px-4">
        {/* Page Header */}
        <div className="mb-8">
          <h1 className="text-3xl md:text-4xl font-bold mb-2">الملف الشخصي</h1>
          <p className="text-gray-600">إدارة معلوماتك الشخصية وإعدادات الأمان</p>
        </div>

        {/* Activity Summary */}
        {activity && (
          <Card className="p-6 mb-6 bg-gradient-to-r from-[#F5411C]/10 to-transparent">
            <div className="flex items-center gap-2 mb-4">
              <Activity className="w-5 h-5 text-[#F5411C]" />
              <h2 className="text-xl font-bold">ملخص النشاط</h2>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-3 bg-white rounded-lg">
                <div className="text-2xl font-bold text-[#F5411C]">{activity.total_orders}</div>
                <div className="text-sm text-gray-600">إجمالي الطلبات</div>
              </div>
              <div className="text-center p-3 bg-white rounded-lg">
                <div className="text-2xl font-bold text-yellow-500">{activity.pending_orders}</div>
                <div className="text-sm text-gray-600">طلبات قيد الانتظار</div>
              </div>
              <div className="text-center p-3 bg-white rounded-lg">
                <div className="text-2xl font-bold text-blue-500">{activity.total_reviews}</div>
                <div className="text-sm text-gray-600">المراجعات</div>
              </div>
              <div className="text-center p-3 bg-white rounded-lg">
                <div className="text-2xl font-bold text-green-500">{activity.total_addresses}</div>
                <div className="text-sm text-gray-600">العناوين</div>
              </div>
            </div>
            <div className="mt-4 text-sm text-gray-600 text-center">
              عضو منذ: {new Date(activity.member_since).toLocaleDateString('ar-EG')}
            </div>
          </Card>
        )}

        {/* Profile Information */}
        <Card className="p-6 mb-6">
          <div className="flex items-center gap-2 mb-6">
            <User className="w-5 h-5 text-[#F5411C]" />
            <h2 className="text-xl font-bold">المعلومات الشخصية</h2>
          </div>

          {profile.provider && (
            <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg flex items-center gap-2">
              <Shield className="w-4 h-4 text-blue-600" />
              <span className="text-sm text-blue-800">
                تم تسجيل الدخول عبر {profile.provider === 'google' ? 'Google' : 'Facebook'}
              </span>
            </div>
          )}

          <form onSubmit={handleUpdateProfile} className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-2">
                الاسم <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <User className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="pr-10"
                  placeholder="أدخل اسمك"
                  maxLength={255}
                  required
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-2">
                البريد الإلكتروني <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Mail className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pr-10"
                  placeholder="example@email.com"
                  required
                />
              </div>
              {profile.email_verified_at ? (
                <p className="text-xs text-green-600 mt-1 flex items-center gap-1">
                  <Shield className="w-3 h-3" /> تم التحقق من البريد الإلكتروني
                </p>
              ) : (
                <p className="text-xs text-yellow-600 mt-1">لم يتم التحقق من البريد الإلكتروني</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-2">رقم الهاتف</label>
              <div className="relative">
                <Phone className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="pr-10"
                  placeholder="+966 XX XXX XXXX"
                />
              </div>
            </div>

            <Button
              type="submit"
              disabled={updating}
              className="w-full bg-[#F5411C] hover:bg-[#e63914]"
            >
              {updating ? 'جارٍ الحفظ...' : 'حفظ التغييرات'}
            </Button>
          </form>
        </Card>

        {/* Password Change */}
        {!profile.provider && (
          <Card className="p-6 mb-6">
            <div className="flex items-center gap-2 mb-6">
              <Lock className="w-5 h-5 text-[#F5411C]" />
              <h2 className="text-xl font-bold">تغيير كلمة المرور</h2>
            </div>

            <form onSubmit={handlePasswordChange} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2">
                  كلمة المرور الحالية <span className="text-red-500">*</span>
                </label>
                <Input
                  type="password"
                  value={currentPassword}
                  onChange={(e) => setCurrentPassword(e.target.value)}
                  placeholder="••••••••"
                  autoComplete="current-password"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">
                  كلمة المرور الجديدة <span className="text-red-500">*</span>
                </label>
                <Input
                  type="password"
                  value={newPassword}
                  onChange={(e) => handlePasswordInput(e.target.value)}
                  placeholder="••••••••"
                  minLength={8}
                  autoComplete="new-password"
                />
                {passwordStrength.score > 0 && (
                  <div className="mt-2">
                    <div className="flex gap-1 mb-1">
                      {[1, 2, 3, 4, 5, 6].map((level) => (
                        <div
                          key={level}
                          className={`h-1 flex-1 rounded ${
                            level <= passwordStrength.score
                              ? passwordStrength.score <= 2
                                ? 'bg-red-500'
                                : passwordStrength.score <= 4
                                ? 'bg-yellow-500'
                                : 'bg-green-500'
                              : 'bg-gray-200'
                          }`}
                        />
                      ))}
                    </div>
                    <p className="text-xs text-gray-600">
                      قوة كلمة المرور: {passwordStrength.message}
                    </p>
                  </div>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">
                  تأكيد كلمة المرور <span className="text-red-500">*</span>
                </label>
                <Input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="••••••••"
                  minLength={8}
                  autoComplete="new-password"
                />
              </div>

              <Button
                type="submit"
                disabled={updating}
                className="w-full bg-[#F5411C] hover:bg-[#e63914]"
              >
                {updating ? 'جارٍ التغيير...' : 'تغيير كلمة المرور'}
              </Button>
            </form>
          </Card>
        )}

        {/* Danger Zone - Delete Account */}
        <Card className="p-6 border-red-200 bg-red-50/50">
          <div className="flex items-center gap-2 mb-4">
            <AlertTriangle className="w-5 h-5 text-red-600" />
            <h2 className="text-xl font-bold text-red-600">منطقة الخطر</h2>
          </div>

          {!showDeleteConfirm ? (
            <div>
              <p className="text-sm text-gray-700 mb-4">
                حذف حسابك إجراء دائم ولا يمكن التراجع عنه. سيتم حذف جميع بياناتك نهائياً.
              </p>
              <Button
                onClick={() => setShowDeleteConfirm(true)}
                variant="outline"
                className="border-red-500 text-red-600 hover:bg-red-50"
              >
                حذف الحساب
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              <p className="text-sm text-red-700 font-medium">
                هذا الإجراء لا يمكن التراجع عنه. الرجاء التأكيد.
              </p>

              <div>
                <label className="block text-sm font-medium mb-2">
                  كلمة المرور <span className="text-red-500">*</span>
                </label>
                <Input
                  type="password"
                  value={deletePassword}
                  onChange={(e) => setDeletePassword(e.target.value)}
                  placeholder="أدخل كلمة المرور للتأكيد"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">
                  اكتب DELETE للتأكيد <span className="text-red-500">*</span>
                </label>
                <Input
                  type="text"
                  value={deleteConfirmation}
                  onChange={(e) => setDeleteConfirmation(e.target.value)}
                  placeholder="DELETE"
                />
              </div>

              <div className="flex gap-3">
                <Button
                  onClick={() => {
                    setShowDeleteConfirm(false);
                    setDeletePassword('');
                    setDeleteConfirmation('');
                  }}
                  variant="outline"
                  className="flex-1"
                  disabled={updating}
                >
                  إلغاء
                </Button>
                <Button
                  onClick={handleDeleteAccount}
                  disabled={updating || !deletePassword || deleteConfirmation !== 'DELETE'}
                  className="flex-1 bg-red-600 hover:bg-red-700"
                >
                  {updating ? 'جارٍ الحذف...' : 'تأكيد الحذف'}
                </Button>
              </div>
            </div>
          )}
        </Card>
      </div>
    </Container>
  );
}
