'use client';

import { useState, useEffect } from 'react';
import { MobileLayout } from '../../../../components/mobile-layout';
import { Bell, Moon, Globe, Lock, User, Check, ChevronRight, X } from 'lucide-react';
import api from '../../../../lib/api-client';

export default function SettingsPage() {
  const [user, setUser] = useState<any>(null);
  const [pushStatus, setPushStatus] = useState<'unknown' | 'enabled' | 'disabled' | 'unsupported' | 'denied'>('unknown');
  const [settings, setSettings] = useState({
    notifications: true,
    soundEnabled: true,
    darkMode: false,
    language: 'en',
    autoSync: true,
    offlineMode: true,
  });
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  
  // Edit Profile State
  const [isEditingProfile, setIsEditingProfile] = useState(false);
  const [profileForm, setProfileForm] = useState({ name: '', email: '' });
  const [profileLoading, setProfileLoading] = useState(false);

  // Change Password State
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [passwordForm, setPasswordForm] = useState({ current_password: '', new_password: '' });
  const [passwordLoading, setPasswordLoading] = useState(false);

  useEffect(() => {
    // Load user from localStorage
    const userData = localStorage.getItem('gcx_fshs_user');
    if (userData) {
      const parsedUser = JSON.parse(userData);
      setUser(parsedUser);
      setProfileForm({ name: parsedUser.full_name || parsedUser.name || '', email: parsedUser.email || '' });
    }

    // Load settings from localStorage
    const savedSettings = localStorage.getItem('gcx_fshs_settings');
    if (savedSettings) {
      setSettings(JSON.parse(savedSettings));
    }

    // Detect push capability/status
    const canPush = typeof window !== 'undefined' && 'serviceWorker' in navigator && 'PushManager' in window;
    if (!canPush) {
      setPushStatus('unsupported');
      return;
    }

    if (typeof Notification !== 'undefined' && Notification.permission === 'denied') {
      setPushStatus('denied');
      return;
    }

    navigator.serviceWorker.ready
      .then((reg) => reg.pushManager.getSubscription())
      .then((sub) => {
        setPushStatus(sub ? 'enabled' : 'disabled');
      })
      .catch(() => setPushStatus('unknown'));
  }, []);

  const urlBase64ToUint8Array = (base64String: string) => {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);
    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  };

  const enablePushNotifications = async () => {
    const canPush = typeof window !== 'undefined' && 'serviceWorker' in navigator && 'PushManager' in window;
    if (!canPush) {
      setPushStatus('unsupported');
      setMessage({ type: 'error', text: 'Push notifications are not supported on this device/browser.' });
      return;
    }

    const permission = await Notification.requestPermission();
    if (permission !== 'granted') {
      setPushStatus('denied');
      setMessage({ type: 'error', text: 'Notifications permission was not granted.' });
      return;
    }

    const { data } = await api.get('/push/vapid-public-key');
    const publicKey = data?.public_key as string | undefined;
    if (!publicKey) {
      setMessage({ type: 'error', text: 'Server is missing VAPID_PUBLIC_KEY.' });
      return;
    }

    const reg = await navigator.serviceWorker.ready;
    let sub = await reg.pushManager.getSubscription();
    if (!sub) {
      sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicKey),
      });
    }

    await api.post('/push/subscriptions', sub.toJSON());
    setPushStatus('enabled');
    setMessage({ type: 'success', text: 'Push notifications enabled.' });
  };

  const disablePushNotifications = async () => {
    const canPush = typeof window !== 'undefined' && 'serviceWorker' in navigator && 'PushManager' in window;
    if (!canPush) {
      setPushStatus('unsupported');
      return;
    }

    const reg = await navigator.serviceWorker.ready;
    const sub = await reg.pushManager.getSubscription();
    if (sub) {
      await api.delete('/push/subscriptions', { data: { endpoint: sub.endpoint } });
      await sub.unsubscribe();
    }

    setPushStatus('disabled');
    setMessage({ type: 'success', text: 'Push notifications disabled.' });
  };

  const sendTestPush = async () => {
    try {
      const { data } = await api.post('/push/test', {});
      const okCount = (data?.results || []).filter((r: any) => r.ok).length;
      setMessage({ type: 'success', text: `Test push sent (${okCount} successful).` });
    } catch (err: any) {
      setMessage({ type: 'error', text: err.response?.data?.error || 'Failed to send test push' });
    }
  };

  const updateSetting = (key: string, value: any) => {
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);
    localStorage.setItem('gcx_fshs_settings', JSON.stringify(newSettings));
    setMessage({ type: 'success', text: 'Setting updated successfully' });
    setTimeout(() => setMessage(null), 2000);
  };

  const handleLogout = () => {
    if (confirm('Are you sure you want to logout?')) {
      localStorage.removeItem('gcx_fshs_token');
      localStorage.removeItem('gcx_fshs_user');
      localStorage.removeItem('gcx_fshs_settings');
      window.location.href = '/login';
    }
  };

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setProfileLoading(true);
    try {
      const { data } = await api.put('/auth/profile', profileForm);
      setUser(data.user);
      localStorage.setItem('gcx_fshs_user', JSON.stringify(data.user));
      setMessage({ type: 'success', text: 'Profile updated successfully' });
      setIsEditingProfile(false);
    } catch (err: any) {
      setMessage({ type: 'error', text: err.response?.data?.error || 'Failed to update profile' });
    } finally {
      setProfileLoading(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordLoading(true);
    try {
      const { data } = await api.put('/auth/password', passwordForm);
      setMessage({ type: 'success', text: data.message || 'Password updated successfully' });
      setIsChangingPassword(false);
      setPasswordForm({ current_password: '', new_password: '' });
    } catch (err: any) {
      setMessage({ type: 'error', text: err.response?.data?.error || 'Failed to change password' });
    } finally {
      setPasswordLoading(false);
    }
  };

  return (
    <MobileLayout>
      <div className="space-y-4 p-4 pb-20">
        {/* Header */}
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <h1 className="text-xl font-bold text-slate-900">Settings</h1>
          <p className="mt-1 text-sm text-slate-600">Manage your preferences</p>
        </div>

        {/* Message Alert */}
        {message && (
          <div className={`rounded-xl border px-4 py-3 ${
            message.type === 'success' 
              ? 'border-green-200 bg-green-50 text-green-800' 
              : 'border-red-200 bg-red-50 text-red-800'
          }`}>
            <div className="flex items-center gap-2">
              <Check className="h-4 w-4" />
              <p className="text-sm font-medium">{message.text}</p>
            </div>
          </div>
        )}

        {/* Account Section */}
        {user && (
          <div className="rounded-xl bg-white p-4 shadow-sm">
            <div className="mb-3 flex items-center justify-between text-slate-700">
              <div className="flex items-center gap-2">
                <User className="h-5 w-5 text-brand" />
                <h2 className="font-semibold">Account</h2>
              </div>
              <button 
                onClick={() => setIsEditingProfile(true)}
                className="text-xs font-medium text-brand hover:underline"
              >
                Edit Profile
              </button>
            </div>
            <div className="space-y-3 border-t border-slate-100 pt-3">
              <div>
                <div className="text-xs text-slate-500">Full Name</div>
                <div className="font-medium text-slate-900">{user.full_name || user.name}</div>
              </div>
              <div>
                <div className="text-xs text-slate-500">Email</div>
                <div className="font-medium text-slate-900">{user.email}</div>
              </div>
              <div>
                <div className="text-xs text-slate-500">Role</div>
                <div className="inline-flex items-center gap-1.5 rounded-full bg-blue-100 px-2.5 py-1 text-xs font-medium text-blue-700">
                  <span className="h-1.5 w-1.5 rounded-full bg-blue-500"></span>
                  {user.role?.replace('_', ' ')}
                </div>
              </div>
              <button 
                onClick={() => setIsChangingPassword(true)}
                className="flex w-full items-center justify-between rounded-lg border border-slate-100 bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100"
              >
                <span>Change Password</span>
                <ChevronRight className="h-4 w-4 text-slate-400" />
              </button>
            </div>
          </div>
        )}

        {/* Edit Profile Modal */}
        {isEditingProfile && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
            <div className="w-full max-w-md rounded-2xl bg-white p-6 shadow-xl">
              <div className="mb-4 flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900">Edit Profile</h3>
                <button
                  onClick={() => setIsEditingProfile(false)}
                  aria-label="Close edit profile"
                  className="text-slate-400 hover:text-slate-600"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              <form onSubmit={handleUpdateProfile} className="space-y-4">
                <div>
                  <label htmlFor="profile_name" className="mb-1 block text-sm font-medium text-slate-700">
                    Full Name
                  </label>
                  <input
                    id="profile_name"
                    type="text"
                    value={profileForm.name}
                    onChange={(e) => setProfileForm({ ...profileForm, name: e.target.value })}
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                    required
                  />
                </div>
                <div>
                  <label htmlFor="profile_email" className="mb-1 block text-sm font-medium text-slate-700">
                    Email
                  </label>
                  <input
                    id="profile_email"
                    type="email"
                    value={profileForm.email}
                    onChange={(e) => setProfileForm({ ...profileForm, email: e.target.value })}
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                    required
                  />
                </div>
                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setIsEditingProfile(false)}
                    className="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={profileLoading}
                    className="flex-1 rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand/90 disabled:opacity-50"
                  >
                    {profileLoading ? 'Saving...' : 'Save Changes'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* Change Password Modal */}
        {isChangingPassword && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
            <div className="w-full max-w-md rounded-2xl bg-white p-6 shadow-xl">
              <div className="mb-4 flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900">Change Password</h3>
                <button
                  onClick={() => setIsChangingPassword(false)}
                  aria-label="Close change password"
                  className="text-slate-400 hover:text-slate-600"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              <form onSubmit={handleChangePassword} className="space-y-4">
                <div>
                  <label htmlFor="current_password" className="mb-1 block text-sm font-medium text-slate-700">
                    Current Password
                  </label>
                  <input
                    id="current_password"
                    type="password"
                    value={passwordForm.current_password}
                    onChange={(e) => setPasswordForm({ ...passwordForm, current_password: e.target.value })}
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                    required
                  />
                </div>
                <div>
                  <label htmlFor="new_password" className="mb-1 block text-sm font-medium text-slate-700">
                    New Password
                  </label>
                  <input
                    id="new_password"
                    type="password"
                    value={passwordForm.new_password}
                    onChange={(e) => setPasswordForm({ ...passwordForm, new_password: e.target.value })}
                    className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none"
                    required
                    minLength={6}
                  />
                </div>
                <div className="flex gap-3 pt-2">
                  <button
                    type="button"
                    onClick={() => setIsChangingPassword(false)}
                    className="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={passwordLoading}
                    className="flex-1 rounded-lg bg-brand px-4 py-2 text-sm font-medium text-white hover:bg-brand/90 disabled:opacity-50"
                  >
                    {passwordLoading ? 'Updating...' : 'Update Password'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* Notifications */}
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <div className="mb-3 flex items-center gap-2 text-slate-700">
            <Bell className="h-5 w-5 text-brand" />
            <h2 className="font-semibold">Notifications</h2>
          </div>
          <div className="space-y-3 border-t border-slate-100 pt-3">
            <label className="flex items-center justify-between">
              <div>
                <div className="font-medium text-slate-900">Push Notifications</div>
                <div className="text-xs text-slate-500">
                  {pushStatus === 'unsupported' && 'Not supported on this device/browser'}
                  {pushStatus === 'denied' && 'Permission denied in browser settings'}
                  {pushStatus === 'enabled' && 'Enabled'}
                  {pushStatus === 'disabled' && 'Disabled'}
                  {pushStatus === 'unknown' && 'Checking…'}
                </div>
              </div>
              <button
                onClick={async () => {
                  if (pushStatus === 'enabled') {
                    await disablePushNotifications();
                    updateSetting('notifications', false);
                    return;
                  }
                  await enablePushNotifications();
                  updateSetting('notifications', true);
                }}
                disabled={pushStatus === 'unsupported' || pushStatus === 'unknown'}
                aria-label="Toggle push notifications"
                className={`relative h-6 w-11 rounded-full transition-colors ${
                  pushStatus === 'enabled' ? 'bg-brand' : 'bg-slate-300'
                }`}
              >
                <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${
                  pushStatus === 'enabled' ? 'translate-x-5' : 'translate-x-0.5'
                }`} />
              </button>
            </label>

            <button
              type="button"
              onClick={sendTestPush}
              disabled={pushStatus !== 'enabled'}
              className="w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
            >
              Send test notification
            </button>
            <label className="flex items-center justify-between">
              <div>
                <div className="font-medium text-slate-900">Sound</div>
                <div className="text-xs text-slate-500">Play sound on notifications</div>
              </div>
              <button
                onClick={() => updateSetting('soundEnabled', !settings.soundEnabled)}
                aria-label="Toggle notification sound"
                className={`relative h-6 w-11 rounded-full transition-colors ${
                  settings.soundEnabled ? 'bg-brand' : 'bg-slate-300'
                }`}
              >
                <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${
                  settings.soundEnabled ? 'translate-x-5' : 'translate-x-0.5'
                }`} />
              </button>
            </label>
          </div>
        </div>

        {/* Appearance */}
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <div className="mb-3 flex items-center gap-2 text-slate-700">
            <Moon className="h-5 w-5 text-brand" />
            <h2 className="font-semibold">Appearance</h2>
          </div>
          <div className="space-y-3 border-t border-slate-100 pt-3">
            <label className="flex items-center justify-between">
              <div>
                <div className="font-medium text-slate-900">Dark Mode</div>
                <div className="text-xs text-slate-500">Use dark color scheme</div>
              </div>
              <button
                onClick={() => updateSetting('darkMode', !settings.darkMode)}
                aria-label="Toggle dark mode"
                className={`relative h-6 w-11 rounded-full transition-colors ${
                  settings.darkMode ? 'bg-brand' : 'bg-slate-300'
                }`}
              >
                <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${
                  settings.darkMode ? 'translate-x-5' : 'translate-x-0.5'
                }`} />
              </button>
            </label>
          </div>
        </div>

        {/* Language */}
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <div className="mb-3 flex items-center gap-2 text-slate-700">
            <Globe className="h-5 w-5 text-brand" />
            <h2 className="font-semibold">Language</h2>
          </div>
          <div className="border-t border-slate-100 pt-3">
            <select
              value={settings.language}
              onChange={(e) => updateSetting('language', e.target.value)}
              aria-label="Language"
              className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:border-brand focus:outline-none focus:ring-2 focus:ring-brand/20"
            >
              <option value="en">English</option>
              <option value="fr">Français</option>
              <option value="tw">Twi</option>
              <option value="ga">Ga</option>
            </select>
          </div>
        </div>

        {/* Data & Sync */}
        <div className="rounded-xl bg-white p-4 shadow-sm">
          <div className="mb-3 flex items-center gap-2 text-slate-700">
            <Lock className="h-5 w-5 text-brand" />
            <h2 className="font-semibold">Data & Sync</h2>
          </div>
          <div className="space-y-3 border-t border-slate-100 pt-3">
            <label className="flex items-center justify-between">
              <div>
                <div className="font-medium text-slate-900">Auto Sync</div>
                <div className="text-xs text-slate-500">Sync data automatically</div>
              </div>
              <button
                onClick={() => updateSetting('autoSync', !settings.autoSync)}
                aria-label="Toggle auto sync"
                className={`relative h-6 w-11 rounded-full transition-colors ${
                  settings.autoSync ? 'bg-brand' : 'bg-slate-300'
                }`}
              >
                <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${
                  settings.autoSync ? 'translate-x-5' : 'translate-x-0.5'
                }`} />
              </button>
            </label>
            <label className="flex items-center justify-between">
              <div>
                <div className="font-medium text-slate-900">Offline Mode</div>
                <div className="text-xs text-slate-500">Save data when offline</div>
              </div>
              <button
                onClick={() => updateSetting('offlineMode', !settings.offlineMode)}
                aria-label="Toggle offline mode"
                className={`relative h-6 w-11 rounded-full transition-colors ${
                  settings.offlineMode ? 'bg-brand' : 'bg-slate-300'
                }`}
              >
                <span className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${
                  settings.offlineMode ? 'translate-x-5' : 'translate-x-0.5'
                }`} />
              </button>
            </label>
          </div>
        </div>

        {/* App Info */}
        <div className="rounded-xl bg-slate-50 p-4">
          <div className="space-y-2 text-center text-sm text-slate-600">
            <div className="font-semibold text-slate-900">GCX FSHS Field v1.0</div>
            <div>School Feeding Programme</div>
            <div className="text-xs">© 2025 All rights reserved</div>
          </div>
        </div>

        {/* Logout Button */}
        <button
          onClick={handleLogout}
          className="w-full rounded-xl bg-red-500 px-4 py-3 font-semibold text-white shadow-sm transition-colors hover:bg-red-600 active:bg-red-700"
        >
          Logout
        </button>

        <div className="h-4"></div>
      </div>
    </MobileLayout>
  );
}
