'use client';

import { useState, useEffect } from 'react';
import { KeyRound, Shield, Bell, Save, CheckCircle2, AlertCircle } from 'lucide-react';
import ChangePasswordDialog from '@/components/auth/ChangePasswordDialog';
import { useNotificationSettings } from '@/hooks/useNotifications';
import { getErrorMessage } from '@/lib/errors';
import type { UpdateNotificationSettingsPayload } from '@/types/notification.types';

export default function AdminSettingsPage() {
  const [showChangePassword, setShowChangePassword] = useState(false);
  const [passwordChanged, setPasswordChanged] = useState(false);

  const { settings, loading, error, updateSettings } = useNotificationSettings();
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [localSettings, setLocalSettings] = useState<UpdateNotificationSettingsPayload | null>(null);

  const currentSettings = localSettings ?? settings ?? {};

  const handlePasswordChanged = () => {
    setPasswordChanged(true);
    setTimeout(() => setPasswordChanged(false), 3000);
  };

  const handleToggle = (key: keyof UpdateNotificationSettingsPayload) => {
    setLocalSettings((prev) => ({
      ...prev,
      [key]: !(currentSettings as any)[key],
    }));
  };

  const handleSaveNotifications = async () => {
    if (!localSettings) return;
    setSaving(true);
    setSaved(false);
    setSaveError(null);
    try {
      await updateSettings(localSettings);
      setLocalSettings(null);
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    } catch (err) {
      setSaveError(getErrorMessage(err));
    } finally {
      setSaving(false);
    }
  };

  const notificationToggles: { key: keyof UpdateNotificationSettingsPayload; label: string; description: string }[] = [
    { key: 'walletNotifications', label: 'Wallet Notifications', description: 'Deposits, withdrawals, and balance changes' },
    { key: 'orderNotifications', label: 'Order Notifications', description: 'Order creation, matching, and status updates' },
    { key: 'tradeNotifications', label: 'Trade Notifications', description: 'Trade execution, disputes, and completions' },
    { key: 'referralNotifications', label: 'Referral Notifications', description: 'Referral signups, commissions, and rewards' },
    { key: 'commissionNotifications', label: 'Commission Notifications', description: 'Commission earnings and payouts' },
    { key: 'securityNotifications', label: 'Security Notifications', description: 'Login alerts, password changes, and security events' },
    { key: 'supportNotifications', label: 'Support Notifications', description: 'Ticket updates and support responses' },
    { key: 'announcementNotifications', label: 'Announcements', description: 'Platform announcements and updates' },
    { key: 'systemNotifications', label: 'System Notifications', description: 'System updates and maintenance alerts' },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Settings</h1>
        <p className="mt-1 text-sm text-slate-400">Manage your account settings</p>
      </div>

      <div className="rounded-xl border border-white/10 bg-white/5 p-6">
        <h2 className="text-lg font-semibold text-white mb-4">Security</h2>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium text-white">Password</p>
            <p className="text-xs text-slate-400">Change your account password</p>
          </div>
          <button
            onClick={() => setShowChangePassword(true)}
            className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700"
          >
            <KeyRound className="h-4 w-4" /> Change Password
          </button>
        </div>
        {passwordChanged && (
          <p className="mt-3 text-sm text-emerald-400">Password changed successfully!</p>
        )}
      </div>

      <div className="rounded-xl border border-white/10 bg-white/5 p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-blue-500/10 p-2">
              <Bell className="h-5 w-5 text-blue-400" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-white">Notification Settings</h2>
              <p className="text-xs text-slate-400">Control which notifications you receive</p>
            </div>
          </div>
          <button
            onClick={handleSaveNotifications}
            disabled={!localSettings || saving}
            className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700 disabled:opacity-50"
          >
            {saved ? (
              <>
                <CheckCircle2 className="h-4 w-4" /> Saved
              </>
            ) : saving ? (
              <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
            ) : (
              <>
                <Save className="h-4 w-4" /> Save Changes
              </>
            )}
          </button>
        </div>

        {(error || saveError) && (
          <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center gap-2">
            <AlertCircle className="h-4 w-4" /> {error ?? saveError}
          </div>
        )}

        {loading ? (
          <p className="text-center text-slate-400 py-4">Loading notification settings...</p>
        ) : (
          <div className="space-y-3">
            {notificationToggles.map((setting) => {
              const isEnabled = (currentSettings as any)[setting.key] ?? true;
              return (
                <div key={setting.key} className="flex items-center justify-between rounded-lg border border-white/5 bg-white/[0.02] p-3">
                  <div>
                    <p className="text-sm font-medium text-white">{setting.label}</p>
                    <p className="text-xs text-slate-400">{setting.description}</p>
                  </div>
                  <label className="relative inline-flex cursor-pointer items-center">
                    <input
                      type="checkbox"
                      checked={isEnabled}
                      onChange={() => handleToggle(setting.key)}
                      className="peer sr-only"
                    />
                    <div className="h-6 w-11 rounded-full bg-slate-700 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-slate-400 after:transition-all peer-checked:bg-blue-500 peer-checked:after:translate-x-full peer-checked:after:bg-white" />
                  </label>
                </div>
              );
            })}
          </div>
        )}
      </div>

      <ChangePasswordDialog
        open={showChangePassword}
        onClose={() => setShowChangePassword(false)}
        onSuccess={handlePasswordChanged}
        title="Change Your Password"
        requireCurrentPassword={true}
      />
    </div>
  );
}
