import { useState, useEffect } from 'react';
import api from '../services/api';
import toast from 'react-hot-toast';
import { useAuth } from '../context/AuthContext';
import { BriefcaseBusiness, Camera, Check, ChevronLeft, ChevronRight, ShieldCheck, UserRound } from 'lucide-react';

export default function Profile({ embedded = false }) {
  const { user, refreshUser } = useAuth();
  const [profile, setProfile] = useState({ name: '', email: '', phone: '', job_title: '', department: '', bio: '', avatar_url: '' });
  const [passwords, setPasswords] = useState({ current_password: '', new_password: '', new_password_confirmation: '' });
  const [saving, setSaving] = useState(false);
  const [savingPass, setSavingPass] = useState(false);
  const [avatarFile, setAvatarFile] = useState(null);
  const [avatarPreview, setAvatarPreview] = useState('');
  const [savingAvatar, setSavingAvatar] = useState(false);
  const [wizardStep, setWizardStep] = useState(0);

  useEffect(() => {
    if (user) {
      setProfile({
        name: user.name || '',
        email: user.email || '',
        phone: user.phone || '',
        job_title: user.job_title || '',
        department: user.department || '',
        bio: user.bio || '',
        avatar_url: user.avatar_url || user.avatar || '',
      });
      setAvatarPreview(user.avatar_url || '');
    }
  }, [user]);

  useEffect(() => {
    if (!avatarFile) return;
    const previewUrl = URL.createObjectURL(avatarFile);
    setAvatarPreview(previewUrl);
    return () => URL.revokeObjectURL(previewUrl);
  }, [avatarFile]);

  const handleSaveProfile = async (e) => {
    e.preventDefault();
    if (!profile.name.trim()) { toast.error('نام الزامی است'); return; }
    setSaving(true);
    try {
      await api.put('/user/profile', profile);
      toast.success('پروفایل به‌روزرسانی شد');
      if (refreshUser) refreshUser();
    } catch (err) { toast.error(err.response?.data?.message || 'خطا'); } finally { setSaving(false); }
  };

  const handleChangePassword = async (e) => {
    e.preventDefault();
    if (!passwords.current_password) { toast.error('رمز فعلی را وارد کنید'); return; }
    if (passwords.new_password !== passwords.new_password_confirmation) { toast.error('رمز جدید مطابقت ندارد'); return; }
    if (passwords.new_password.length < 6) { toast.error('رمز جدید حداقل ۶ کاراکتر'); return; }
    setSavingPass(true);
    try {
      await api.put('/user/password', passwords);
      toast.success('رمز عبور تغییر کرد');
      setPasswords({ current_password: '', new_password: '', new_password_confirmation: '' });
    } catch (err) { toast.error(err.response?.data?.message || 'خطا'); } finally { setSavingPass(false); }
  };

  const handleAvatarUpload = async (file = avatarFile) => {
    if (!file) { toast.error('ابتدا یک عکس انتخاب کنید'); return; }
    const formData = new FormData();
    formData.append('avatar', file);
    setSavingAvatar(true);
    try {
      await api.post('/user/avatar', formData, { headers: { 'Content-Type': 'multipart/form-data' } });
      toast.success('عکس پروفایل به‌روزرسانی شد');
      setAvatarFile(null);
      if (refreshUser) refreshUser();
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در آپلود عکس');
    } finally {
      setSavingAvatar(false);
    }
  };

  const handleAvatarChange = (e) => {
    const file = e.target.files?.[0] || null;
    if (!file) return;
    setAvatarFile(file);
    handleAvatarUpload(file);
    e.target.value = '';
  };

  const wizardSteps = [
    { label: 'هویت', icon: UserRound },
    { label: 'اطلاعات کاری', icon: BriefcaseBusiness },
    { label: 'امنیت', icon: ShieldCheck },
  ];

  const identityHeader = (
    <div className="profile-identity">
      <label className={`profile-avatar-wrap ${savingAvatar ? 'uploading' : ''}`} title={savingAvatar ? 'در حال آپلود عکس' : 'تغییر عکس پروفایل'}>
        {avatarPreview ? (
          <img className="profile-avatar-img" src={avatarPreview} alt={user?.name || 'avatar'} />
        ) : (
          <div className="avatar avatar-xl" style={{ width: 88, height: 88 }}>
            <Camera size={28} strokeWidth={1.8} />
          </div>
        )}
        <input className="profile-avatar-input" type="file" accept="image/png,image/jpeg,image/webp" onChange={handleAvatarChange} disabled={savingAvatar} />
      </label>
      <div>
        <h2>{user?.name}</h2>
        <div>{user?.email}</div>
        <small>{user?.job_title} {user?.job_title && user?.department ? '|' : ''} {user?.department}</small>
      </div>
    </div>
  );

  if (embedded) {
    return (
      <div className="profile-wizard">
        <div className="modal-wizard-steps" role="tablist" aria-label="مراحل پروفایل">
          {wizardSteps.map((step, index) => {
            const Icon = step.icon;
            return (
              <button
                key={step.label}
                type="button"
                role="tab"
                aria-selected={wizardStep === index}
                className={wizardStep === index ? 'active' : wizardStep > index ? 'complete' : ''}
                onClick={() => setWizardStep(index)}
              >
                <span>{wizardStep > index ? <Check size={16} /> : <Icon size={16} />}</span>
                {step.label}
              </button>
            );
          })}
        </div>

        <div className="profile-wizard-panel" role="tabpanel">
          {wizardStep === 0 && (
            <>
              {identityHeader}
              <form onSubmit={handleSaveProfile} className="profile-step-form">
                <div className="grid grid-2">
                  <div className="form-group"><label className="form-label" htmlFor="profile-name">نام</label><input id="profile-name" className="form-input" value={profile.name} onChange={e => setProfile({...profile, name: e.target.value})} /></div>
                  <div className="form-group"><label className="form-label" htmlFor="profile-email">ایمیل</label><input id="profile-email" className="form-input" type="email" value={profile.email} onChange={e => setProfile({...profile, email: e.target.value})} /></div>
                </div>
                <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره هویت'}</button>
              </form>
            </>
          )}

          {wizardStep === 1 && (
            <form onSubmit={handleSaveProfile} className="profile-step-form">
              <div className="grid grid-3">
                <div className="form-group"><label className="form-label" htmlFor="profile-phone">شماره تماس</label><input id="profile-phone" className="form-input" value={profile.phone} onChange={e => setProfile({...profile, phone: e.target.value})} /></div>
                <div className="form-group"><label className="form-label" htmlFor="profile-job">سمت</label><input id="profile-job" className="form-input" value={profile.job_title} onChange={e => setProfile({...profile, job_title: e.target.value})} /></div>
                <div className="form-group"><label className="form-label" htmlFor="profile-department">دپارتمان</label><input id="profile-department" className="form-input" value={profile.department} onChange={e => setProfile({...profile, department: e.target.value})} /></div>
              </div>
              <div className="form-group"><label className="form-label" htmlFor="profile-bio">بیوگرافی</label><textarea id="profile-bio" className="form-textarea" value={profile.bio} onChange={e => setProfile({...profile, bio: e.target.value})} /></div>
              <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره اطلاعات کاری'}</button>
            </form>
          )}

          {wizardStep === 2 && (
            <form onSubmit={handleChangePassword} className="profile-step-form">
              <div className="grid grid-3">
                <div className="form-group"><label className="form-label" htmlFor="current-password">رمز عبور فعلی</label><input id="current-password" className="form-input" type="password" autoComplete="current-password" value={passwords.current_password} onChange={e => setPasswords({...passwords, current_password: e.target.value})} /></div>
                <div className="form-group"><label className="form-label" htmlFor="new-password">رمز عبور جدید</label><input id="new-password" className="form-input" type="password" autoComplete="new-password" value={passwords.new_password} onChange={e => setPasswords({...passwords, new_password: e.target.value})} /></div>
                <div className="form-group"><label className="form-label" htmlFor="confirm-password">تکرار رمز جدید</label><input id="confirm-password" className="form-input" type="password" autoComplete="new-password" value={passwords.new_password_confirmation} onChange={e => setPasswords({...passwords, new_password_confirmation: e.target.value})} /></div>
              </div>
              <button type="submit" className="btn btn-primary" disabled={savingPass}>{savingPass ? 'در حال تغییر...' : 'تغییر رمز عبور'}</button>
            </form>
          )}
        </div>

        <div className="profile-wizard-navigation">
          <button type="button" className="btn btn-secondary" onClick={() => setWizardStep((step) => Math.max(0, step - 1))} disabled={wizardStep === 0}>
            <ChevronRight size={17} />
            قبلی
          </button>
          <span>مرحله {wizardStep + 1} از {wizardSteps.length}</span>
          <button type="button" className="btn btn-secondary" onClick={() => setWizardStep((step) => Math.min(wizardSteps.length - 1, step + 1))} disabled={wizardStep === wizardSteps.length - 1}>
            بعدی
            <ChevronLeft size={17} />
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="page-container" style={{ maxWidth: 720, margin: '0 auto' }}>
      <div className="page-header" />

      <div className="card" style={{ padding: '1.5rem', marginBottom: '1.5rem' }}>
        {identityHeader}

        <form onSubmit={handleSaveProfile}>
          <div className="grid grid-2">
            <div className="form-group"><label className="form-label">نام</label><input className="form-input" value={profile.name} onChange={e => setProfile({...profile, name: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">ایمیل</label><input className="form-input" type="email" value={profile.email} onChange={e => setProfile({...profile, email: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">شماره تماس</label><input className="form-input" value={profile.phone} onChange={e => setProfile({...profile, phone: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">سمت</label><input className="form-input" value={profile.job_title} onChange={e => setProfile({...profile, job_title: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">دپارتمان</label><input className="form-input" value={profile.department} onChange={e => setProfile({...profile, department: e.target.value})} /></div>
          </div>
          <div className="form-group"><label className="form-label">بیوگرافی</label><textarea className="form-textarea" value={profile.bio} onChange={e => setProfile({...profile, bio: e.target.value})} /></div>
          <div style={{ marginTop: '1rem' }}>
            <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? 'در حال ذخیره...' : 'ذخیره اطلاعات'}</button>
          </div>
        </form>
      </div>

      <div className="card" style={{ padding: '1.5rem' }}>
        <h3 style={{ fontSize: '1rem', fontWeight: 600, marginBottom: '1rem' }}>تغییر رمز عبور</h3>
        <form onSubmit={handleChangePassword}>
          <div className="grid grid-2">
            <div className="form-group"><label className="form-label">رمز عبور فعلی</label><input className="form-input" type="password" value={passwords.current_password} onChange={e => setPasswords({...passwords, current_password: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">رمز عبور جدید</label><input className="form-input" type="password" value={passwords.new_password} onChange={e => setPasswords({...passwords, new_password: e.target.value})} /></div>
            <div className="form-group"><label className="form-label">تکرار رمز جدید</label><input className="form-input" type="password" value={passwords.new_password_confirmation} onChange={e => setPasswords({...passwords, new_password_confirmation: e.target.value})} /></div>
          </div>
          <div style={{ marginTop: '1rem' }}>
            <button type="submit" className="btn btn-primary" disabled={savingPass}>{savingPass ? 'در حال تغییر...' : 'تغییر رمز عبور'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}
