'use client';

import { useState, useEffect } from 'react';
import { Bell, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

interface NotificationsCardProps {
  settings: Record<string, string>;
  onSave: (updates: Record<string, string>) => Promise<void>;
}

const notificationOptions = [
  {
    key: 'notify_email_alerts',
    label: 'Email Alerts',
    description: 'Receive email notifications for important events',
  },
  {
    key: 'notify_sms_failures',
    label: 'SMS Delivery Failures',
    description: 'Get notified when SMS messages fail to deliver',
  },
  {
    key: 'notify_new_leads',
    label: 'New Lead Alerts',
    description: 'Alert when a new contact initiates conversation',
  },
];

export default function NotificationsCard({ settings, onSave }: NotificationsCardProps) {
  const [values, setValues] = useState<Record<string, boolean>>({});
  const [saving, setSaving] = useState<string | null>(null);

  useEffect(() => {
    const v: Record<string, boolean> = {};
    for (const opt of notificationOptions) {
      v[opt.key] = settings[opt.key] === 'true';
    }
    setValues(v);
  }, [settings]);

  async function handleToggle(key: string) {
    const newVal = !values[key];
    setValues((prev) => ({ ...prev, [key]: newVal }));
    setSaving(key);
    try {
      await onSave({ [key]: String(newVal) });
    } catch {
      // Revert on failure
      setValues((prev) => ({ ...prev, [key]: !newVal }));
    } finally {
      setSaving(null);
    }
  }

  return (
    <div className="card p-6 space-y-5">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-yellow-500/10 border border-yellow-500/20">
          <Bell className="h-5 w-5 text-yellow-400" />
        </div>
        <div>
          <h3 className="text-sm font-semibold text-white">Notifications</h3>
          <p className="text-xs text-slate-500">Configure alert preferences</p>
        </div>
      </div>

      {/* Toggle rows */}
      <div className="space-y-1">
        {notificationOptions.map((opt) => {
          const isOn = values[opt.key] ?? false;
          const isSaving = saving === opt.key;

          return (
            <div
              key={opt.key}
              className="flex items-center justify-between rounded-lg px-4 py-3 transition-colors hover:bg-slate-800/30"
            >
              <div className="min-w-0 mr-4">
                <p className="text-sm font-medium text-slate-200">{opt.label}</p>
                <p className="text-xs text-slate-500 mt-0.5">{opt.description}</p>
              </div>

              <button
                onClick={() => handleToggle(opt.key)}
                disabled={isSaving}
                className={cn(
                  'relative inline-flex h-6 w-11 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none',
                  isOn ? 'bg-cyan-500' : 'bg-slate-600'
                )}
              >
                {isSaving ? (
                  <span className="absolute inset-0 flex items-center justify-center">
                    <Loader2 className="h-3 w-3 animate-spin text-white" />
                  </span>
                ) : (
                  <span
                    className={cn(
                      'inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform duration-200 ease-in-out',
                      isOn ? 'translate-x-5' : 'translate-x-0'
                    )}
                  />
                )}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
