import { useEffect, useState } from 'react';
import { BellRing, LogOut, LockKeyhole, Palette, RefreshCcw, Smartphone, UserRound } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import api from '../services/api';
import { useAuth } from '../context/AuthContext';
import { usePwaNotification } from './PwaNotificationProvider';
import PwaProfileHeader from './PwaProfileHeader';
import PwaAccountInfoCard from './PwaAccountInfoCard';
import PwaAccessSummary from './PwaAccessSummary';
import PwaThemeSelector from './PwaThemeSelector';
import PwaNotificationSettings from './PwaNotificationSettings';
import PwaPushNotificationStatus from './PwaPushNotificationStatus';
import PwaInstallStatusCard from './PwaInstallStatusCard';
import PwaChangePasswordSheet from './PwaChangePasswordSheet';
import PwaBottomSheet from './PwaBottomSheet';

export default function PwaProfilePage() {
  const { user: authUser, logout } = useAuth();
  const { notify } = usePwaNotification();
  const navigate = useNavigate();
  const [profile, setProfile] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [passwordOpen, setPasswordOpen] = useState(false);
  const [logoutOpen, setLogoutOpen] = useState(false);

  const fetchProfile = async () => {
    setLoading(true);
    setError('');
    try {
      const { data } = await api.get('/pwa/profile');
      setProfile(data.data);
    } catch (err) {
      setError(err.response?.data?.message || 'خطا در دریافت پروفایل');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProfile();
  }, []);

  useEffect(() => {
    if (!authUser) return;
    setProfile((current) => current ? ({ ...current, user: { ...current.user, ...authUser } }) : current);
  }, [authUser]);

  const doLogout = async () => {
    await logout();
    navigate('/login', { replace: true });
  };

  if (loading) return <div className="pwa-skeleton detail" />;
  if (error) {
    return (
      <section className="pwa-state-card error">
        <strong>{error}</strong>
        <button type="button" onClick={fetchProfile}><RefreshCcw size={16} /> تلاش دوباره</button>
      </section>
    );
  }

  const user = profile?.user && authUser ? { ...profile.user, ...authUser } : profile?.user || authUser;

  return (
    <div className="pwa-profile-page">
      <PwaProfileHeader user={user} />
      <PwaAccountInfoCard user={user} />
      <PwaAccessSummary access={profile?.access_summary} />
      <div className="pwa-appearance-settings-anchor"><PwaThemeSelector /></div>

      <section className="pwa-card-section">
        <div className="pwa-section-title">
          <h2>تنظیمات سریع</h2>
        </div>
        <div className="pwa-settings-list">
          <button type="button" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}><UserRound size={17} /><span>اطلاعات حساب</span></button>
          <button type="button" onClick={() => document.querySelector('.pwa-appearance-settings-anchor')?.scrollIntoView({ behavior: 'smooth' })}><Palette size={17} /><span>حالت نمایش</span></button>
          <button type="button" onClick={() => document.querySelector('.pwa-notification-settings-anchor')?.scrollIntoView({ behavior: 'smooth' })}><BellRing size={17} /><span>تنظیمات اعلان‌ها</span></button>
          {profile?.capabilities?.can_change_password && <button type="button" onClick={() => setPasswordOpen(true)}><LockKeyhole size={17} /><span>تغییر رمز عبور</span></button>}
          <button type="button" onClick={() => document.querySelector('.pwa-install-status-anchor')?.scrollIntoView({ behavior: 'smooth' })}><Smartphone size={17} /><span>وضعیت نصب برنامه</span></button>
        </div>
      </section>

      <div className="pwa-notification-settings-anchor"><PwaNotificationSettings /></div>
      <PwaPushNotificationStatus pushReady={profile?.capabilities?.push_backend_ready} />
      <div className="pwa-install-status-anchor"><PwaInstallStatusCard /></div>

      <section className="pwa-card-section pwa-logout-card">
        <button type="button" onClick={() => setLogoutOpen(true)}><LogOut size={18} /> خروج از حساب</button>
      </section>

      <PwaChangePasswordSheet
        open={passwordOpen}
        onClose={() => setPasswordOpen(false)}
        onSuccess={() => notify({ tone: 'success', title: 'رمز عبور', message: 'رمز عبور با موفقیت تغییر یافت.' })}
      />

      <PwaBottomSheet
        open={logoutOpen}
        title="خروج از حساب"
        onClose={() => setLogoutOpen(false)}
        footer={(
          <>
            <button type="button" className="pwa-sheet-cancel" onClick={() => setLogoutOpen(false)}>انصراف</button>
            <button type="button" className="pwa-sheet-submit danger" onClick={doLogout}>خروج از حساب</button>
          </>
        )}
      >
        <p className="pwa-profile-note">آیا می‌خواهید از حساب خارج شوید؟</p>
      </PwaBottomSheet>
    </div>
  );
}
