'use client';
import { useState } from 'react';
import { useAuth } from '../../lib/authContext';
import { useRouter } from 'next/navigation';

const TABS = ['Profile', 'Security', 'Notifications', 'System', 'About'];

interface Props {
  Layout: React.ComponentType<{ children: React.ReactNode; title: string; breadcrumb?: string }>;
}

export default function SettingsContent({ Layout }: Props) {
  const { user, logout } = useAuth();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('Profile');
  const [toast, setToast] = useState('');
  const [profileForm, setProfileForm] = useState({
    name: user?.name || '',
    email: user?.email || '',
    phone: '+254 700 000 000',
    department: user?.dept || 'Administration',
    jobTitle: user?.position || 'Staff',
  });
  const [securityForm, setSecurityForm] = useState({ current: '', newPass: '', confirm: '' });
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [securityError, setSecurityError] = useState('');
  const [notifSettings, setNotifSettings] = useState({
    leaveRequests: true,
    appraisalUpdates: true,
    payrollAlerts: true,
    trainingReminders: false,
    systemAlerts: true,
    emailDigest: false,
  });
  const [sysSettings, setSysSettings] = useState({
    language: 'English',
    timezone: 'Africa/Nairobi (EAT)',
    dateFormat: 'DD/MM/YYYY',
    theme: 'Light',
  });

  const showToast = (msg: string) => {
    setToast(msg);
    setTimeout(() => setToast(''), 3000);
  };

  const getStrength = (p: string) => {
    let score = 0;
    if (p.length >= 8) score++;
    if (/[A-Z]/.test(p)) score++;
    if (/[0-9]/.test(p)) score++;
    if (/[^A-Za-z0-9]/.test(p)) score++;
    return score;
  };

  const strength = getStrength(securityForm.newPass);
  const strengthLabel = ['', 'Weak', 'Fair', 'Good', 'Strong'][strength];
  const strengthColor = ['', '#ef4444', '#f59e0b', '#3b82f6', '#22c55e'][strength];

  const handlePasswordSave = () => {
    setSecurityError('');
    if (!securityForm.current) { setSecurityError('Enter your current password.'); return; }
    if (securityForm.newPass.length < 8) { setSecurityError('Password must be at least 8 characters.'); return; }
    if (strength < 4) { setSecurityError('Password must have uppercase, lowercase, numbers, and symbols.'); return; }
    if (securityForm.newPass !== securityForm.confirm) { setSecurityError('Passwords do not match.'); return; }
    setSecurityForm({ current: '', newPass: '', confirm: '' });
    showToast('Password updated successfully!');
  };

  const BRAND = '#B22698';
  const BRAND_GRAD = `linear-gradient(135deg, #b828a0 0%, ${BRAND} 100%)`;

  return (
    <Layout title="Settings">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2 animate-pulse">
          <div className="w-5 h-5 flex items-center justify-center"><i className="ri-checkbox-circle-line text-lg"></i></div>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="flex gap-6">
        <div className="w-56 flex-shrink-0">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="p-5 text-center" style={{ background: BRAND_GRAD }}>
              <div className="w-16 h-16 rounded-full bg-yellow-400 flex items-center justify-center text-purple-900 font-bold text-2xl mx-auto mb-2">
                {user?.avatar || 'U'}
              </div>
              <p className="text-white font-semibold text-sm">{user?.name}</p>
              <p className="text-pink-200 text-xs mt-0.5 capitalize">{user?.role}</p>
            </div>
            <nav className="p-3">
              {TABS.map(tab => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium cursor-pointer transition-all mb-1 ${activeTab === tab ? 'text-white' : 'text-gray-600 hover:bg-gray-50'}`}
                  style={activeTab === tab ? { background: BRAND_GRAD } : {}}
                >
                  <div className="w-4 h-4 flex items-center justify-center">
                    <i className={`${tab === 'Profile' ? 'ri-user-line' : tab === 'Security' ? 'ri-shield-keyhole-line' : tab === 'Notifications' ? 'ri-notification-3-line' : tab === 'System' ? 'ri-settings-3-line' : 'ri-information-line'} text-sm`}></i>
                  </div>
                  {tab}
                </button>
              ))}
              <div className="border-t border-gray-100 mt-2 pt-2">
                <button onClick={() => { logout(); router.replace('/login'); }}
                  className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium cursor-pointer text-red-600 hover:bg-red-50 transition-all">
                  <div className="w-4 h-4 flex items-center justify-center"><i className="ri-logout-box-r-line text-sm"></i></div>
                  Sign Out
                </button>
              </div>
            </nav>
          </div>
        </div>

        <div className="flex-1">
          {activeTab === 'Profile' && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Profile Information</h2>
              <p className="text-sm text-gray-500 mb-6">Update your personal details and contact information</p>
              <div className="flex items-center gap-5 mb-6 p-5 bg-gray-50 rounded-xl">
                <div className="w-20 h-20 rounded-2xl flex items-center justify-center text-purple-900 font-bold text-3xl flex-shrink-0" style={{ background: 'linear-gradient(135deg, #f6d365, #fda085)' }}>
                  {user?.avatar || 'U'}
                </div>
                <div>
                  <p className="font-semibold text-gray-800">{user?.name}</p>
                  <p className="text-sm text-gray-500">{user?.email}</p>
                  <button className="mt-2 text-xs px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-100 cursor-pointer whitespace-nowrap">Change Avatar</button>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4 mb-6">
                {[
                  { label: 'Full Name', key: 'name', type: 'text' },
                  { label: 'Email Address', key: 'email', type: 'email' },
                  { label: 'Phone Number', key: 'phone', type: 'tel' },
                  { label: 'Department', key: 'department', type: 'text' },
                  { label: 'Job Title', key: 'jobTitle', type: 'text' },
                ].map(f => (
                  <div key={f.key} className={f.key === 'jobTitle' ? 'col-span-2' : ''}>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">{f.label}</label>
                    <input
                      type={f.type}
                      value={(profileForm as any)[f.key]}
                      onChange={e => setProfileForm(p => ({ ...p, [f.key]: e.target.value }))}
                      className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none transition-all"
                    />
                  </div>
                ))}
              </div>
              <button onClick={() => showToast('Profile updated successfully!')}
                className="px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND_GRAD }}>
                Save Changes
              </button>
            </div>
          )}

          {activeTab === 'Security' && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Security Settings</h2>
              <p className="text-sm text-gray-500 mb-6">Change your password. Must include uppercase, lowercase, numbers, and symbols.</p>
              <div className="space-y-4 mb-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Current Password</label>
                  <div className="relative">
                    <input type={showCurrent ? 'text' : 'password'} value={securityForm.current} onChange={e => setSecurityForm(p => ({ ...p, current: e.target.value }))}
                      placeholder="Enter current password" className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none pr-12" />
                    <button type="button" onClick={() => setShowCurrent(v => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer">
                      <i className={`${showCurrent ? 'ri-eye-off-line' : 'ri-eye-line'} text-gray-400 text-sm`}></i>
                    </button>
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">New Password</label>
                  <div className="relative">
                    <input type={showNew ? 'text' : 'password'} value={securityForm.newPass} onChange={e => setSecurityForm(p => ({ ...p, newPass: e.target.value }))}
                      placeholder="Enter new password" className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none pr-12" />
                    <button type="button" onClick={() => setShowNew(v => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer">
                      <i className={`${showNew ? 'ri-eye-off-line' : 'ri-eye-line'} text-gray-400 text-sm`}></i>
                    </button>
                  </div>
                  {securityForm.newPass && (
                    <div className="mt-2">
                      <div className="flex gap-1 mb-1">
                        {[1, 2, 3, 4].map(i => (
                          <div key={i} className="h-1.5 flex-1 rounded-full transition-all" style={{ background: i <= strength ? strengthColor : '#e5e7eb' }}></div>
                        ))}
                      </div>
                      <p className="text-xs font-medium" style={{ color: strengthColor }}>{strengthLabel} password</p>
                    </div>
                  )}
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Confirm New Password</label>
                  <div className="relative">
                    <input type={showConfirm ? 'text' : 'password'} value={securityForm.confirm} onChange={e => setSecurityForm(p => ({ ...p, confirm: e.target.value }))}
                      placeholder="Confirm new password" className="w-full border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none pr-12" />
                    <button type="button" onClick={() => setShowConfirm(v => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center cursor-pointer">
                      <i className={`${showConfirm ? 'ri-eye-off-line' : 'ri-eye-line'} text-gray-400 text-sm`}></i>
                    </button>
                    {securityForm.confirm && securityForm.newPass === securityForm.confirm && (
                      <div className="absolute right-10 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
                        <i className="ri-checkbox-circle-fill text-green-500 text-base"></i>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {securityError && (
                <div className="flex items-center gap-2 bg-red-50 border border-red-200 rounded-xl px-3 py-2.5 mb-4">
                  <i className="ri-error-warning-line text-red-500 text-sm flex-shrink-0"></i>
                  <p className="text-red-600 text-sm">{securityError}</p>
                </div>
              )}

              <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl mb-4">
                <p className="text-sm font-semibold text-amber-800 mb-2">Password Requirements</p>
                <div className="space-y-1">
                  {[
                    { rule: 'Minimum 8 characters', met: securityForm.newPass.length >= 8 },
                    { rule: 'At least one uppercase letter (A-Z)', met: /[A-Z]/.test(securityForm.newPass) },
                    { rule: 'At least one lowercase letter (a-z)', met: /[a-z]/.test(securityForm.newPass) },
                    { rule: 'At least one number (0-9)', met: /[0-9]/.test(securityForm.newPass) },
                    { rule: 'At least one symbol (!@#$%...)', met: /[^A-Za-z0-9]/.test(securityForm.newPass) },
                  ].map((r, i) => (
                    <div key={i} className="flex items-center gap-2 text-xs">
                      <i className={`${r.met ? 'ri-checkbox-circle-fill text-green-500' : 'ri-circle-line text-gray-300'} text-sm`}></i>
                      <span className={r.met ? 'text-green-700' : 'text-amber-700'}>{r.rule}</span>
                    </div>
                  ))}
                </div>
              </div>

              <button onClick={handlePasswordSave}
                className="px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND_GRAD }}>
                Update Password
              </button>
            </div>
          )}

          {activeTab === 'Notifications' && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-800 mb-1">Notification Preferences</h2>
              <p className="text-sm text-gray-500 mb-6">Choose which notifications you want to receive</p>
              <div className="space-y-4">
                {[
                  { key: 'leaveRequests', label: 'Leave Requests', desc: 'Notify when employees submit leave requests' },
                  { key: 'appraisalUpdates', label: 'Appraisal Updates', desc: 'Notify when appraisals are submitted or completed' },
                  { key: 'payrollAlerts', label: 'Payroll Alerts', desc: 'Notify about payroll deadlines and processing' },
                  { key: 'trainingReminders', label: 'Training Reminders', desc: 'Reminders for upcoming training programs' },
                  { key: 'systemAlerts', label: 'System Alerts', desc: 'Critical system and security alerts' },
                  { key: 'emailDigest', label: 'Daily Email Digest', desc: 'Receive a daily summary of all activities' },
                ].map(n => (
                  <div key={n.key} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                    <div>
                      <p className="text-sm font-semibold text-gray-700">{n.label}</p>
                      <p className="text-xs text-gray-500 mt-0.5">{n.desc}</p>
                    </div>
                    <button onClick={() => setNotifSettings(s => ({ ...s, [n.key]: !(s as any)[n.key] }))}
                      className={`relative w-11 h-6 rounded-full transition-all cursor-pointer flex-shrink-0 ${(notifSettings as any)[n.key] ? '' : 'bg-gray-200'}`}
                      style={(notifSettings as any)[n.key] ? { background: BRAND_GRAD } : {}}>
                      <div className={`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow-sm transition-all`} style={(notifSettings as any)[n.key] ? { left: '22px' } : { left: '2px' }}></div>
                    </button>
                  </div>
                ))}
              </div>
              <button onClick={() => showToast('Notification preferences saved!')}
                className="mt-6 px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND_GRAD }}>
                Save Preferences
              </button>
            </div>
          )}

          {activeTab === 'System' && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-800 mb-1">System Preferences</h2>
              <p className="text-sm text-gray-500 mb-6">Configure language, timezone, and display options</p>
              <div className="space-y-4 mb-6">
                {[
                  { label: 'Language', key: 'language', options: ['English', 'Kiswahili'] },
                  { label: 'Timezone', key: 'timezone', options: ['Africa/Nairobi (EAT)', 'UTC'] },
                  { label: 'Date Format', key: 'dateFormat', options: ['DD/MM/YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD'] },
                  { label: 'Theme', key: 'theme', options: ['Light', 'Dark'] },
                ].map(s => (
                  <div key={s.key}>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">{s.label}</label>
                    <div className="flex gap-2">
                      {s.options.map(opt => (
                        <button key={opt} onClick={() => setSysSettings(p => ({ ...p, [s.key]: opt }))}
                          className={`px-4 py-2 rounded-xl text-sm font-medium cursor-pointer whitespace-nowrap border transition-all ${(sysSettings as any)[s.key] === opt ? 'text-white border-transparent' : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-pink-300'}`}
                          style={(sysSettings as any)[s.key] === opt ? { background: BRAND_GRAD } : {}}>
                          {opt}
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <button onClick={() => showToast('System preferences saved!')}
                className="px-6 py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
                style={{ background: BRAND_GRAD }}>
                Save Settings
              </button>
            </div>
          )}

          {activeTab === 'About' && (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-bold text-gray-800 mb-1">About the System</h2>
              <p className="text-sm text-gray-500 mb-6">System information and version details</p>
              <div className="space-y-4">
                {[
                  { label: 'System Name', value: 'Uwezo Fund HRMS' },
                  { label: 'Version', value: 'v2.0.1' },
                  { label: 'Last Updated', value: 'May 2026' },
                  { label: 'Organization', value: 'Uwezo Fund' },
                  { label: 'Environment', value: 'Production' },
                  { label: 'Support Email', value: 'support@uwezo.go.ke' },
                ].map(item => (
                  <div key={item.label} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
                    <span className="text-sm text-gray-500">{item.label}</span>
                    <span className="text-sm font-semibold text-gray-800">{item.value}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
}