import { useState, useEffect } from 'react';
import {
  useNotificationConfig,
  useUpdateNotificationConfig,
  useNotificationHistory,
} from '../../api/tradingHooks';
import type { NotificationRecord } from '../../api/tradingHooks';
import { Card, LoadingSpinner, StatusBadge } from '../../components/ui';
import { DataTable, type Column } from '../../components/DataTable';

const notifColumns: Column<NotificationRecord>[] = [
  {
    key: 'channel',
    header: 'Channel',
    render: (r) => <span className="capitalize">{r.channel}</span>,
  },
  {
    key: 'event_type',
    header: 'Event',
    render: (r) => <span className="text-xs">{r.event_type}</span>,
  },
  {
    key: 'message',
    header: 'Message',
    render: (r) => <span className="max-w-xs truncate text-xs text-gray-400">{r.message}</span>,
  },
  {
    key: 'delivery_status',
    header: 'Status',
    render: (r) => <StatusBadge status={r.delivery_status} />,
  },
  {
    key: 'created_at',
    header: 'Sent',
    render: (r) => <span className="text-xs">{new Date(r.created_at).toLocaleString()}</span>,
  },
];

export function NotificationPreferences() {
  const { data: config, isLoading } = useNotificationConfig();
  const { data: history } = useNotificationHistory();
  const updateConfig = useUpdateNotificationConfig();

  const [smsEnabled, setSmsEnabled] = useState(false);
  const [emailEnabled, setEmailEnabled] = useState(false);
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');

  useEffect(() => {
    if (config) {
      setSmsEnabled(config.sms_enabled);
      setEmailEnabled(config.email_enabled);
      setPhone(config.phone_number ?? '');
      setEmail(config.email_recipient ?? '');
    }
  }, [config]);

  function handleSave() {
    updateConfig.mutate({
      sms_enabled: smsEnabled,
      email_enabled: emailEnabled,
      phone_number: phone || null,
      email_recipient: email || null,
    });
  }

  if (isLoading) return <LoadingSpinner />;

  return (
    <div className="space-y-4">
      {/* Channel Toggles */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">Notification Channels</h2>
        <div className="space-y-4">
          {/* SMS */}
          <div className="flex items-start gap-4">
            <button
              onClick={() => setSmsEnabled(!smsEnabled)}
              className={`relative mt-0.5 inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 focus:ring-offset-surface-900 ${
                smsEnabled ? 'bg-brand-600' : 'bg-surface-700'
              }`}
              role="switch"
              aria-checked={smsEnabled}
              aria-label="Toggle SMS notifications"
            >
              <span
                className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow ring-0 transition-transform ${
                  smsEnabled ? 'translate-x-5' : 'translate-x-0'
                }`}
              />
            </button>
            <div className="flex-1">
              <div className="text-sm text-gray-300">SMS Notifications</div>
              <input
                type="tel"
                placeholder="Phone number…"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="mt-1 w-full max-w-xs rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 placeholder-gray-500 focus:border-brand-500 focus:outline-none"
                aria-label="Phone number"
              />
            </div>
          </div>

          {/* Email */}
          <div className="flex items-start gap-4">
            <button
              onClick={() => setEmailEnabled(!emailEnabled)}
              className={`relative mt-0.5 inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 focus:ring-offset-surface-900 ${
                emailEnabled ? 'bg-brand-600' : 'bg-surface-700'
              }`}
              role="switch"
              aria-checked={emailEnabled}
              aria-label="Toggle email notifications"
            >
              <span
                className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow ring-0 transition-transform ${
                  emailEnabled ? 'translate-x-5' : 'translate-x-0'
                }`}
              />
            </button>
            <div className="flex-1">
              <div className="text-sm text-gray-300">Email Notifications</div>
              <input
                type="email"
                placeholder="Email address…"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1 w-full max-w-xs rounded-md border border-surface-700 bg-surface-950 px-2 py-1.5 text-sm text-gray-200 placeholder-gray-500 focus:border-brand-500 focus:outline-none"
                aria-label="Email address"
              />
            </div>
          </div>
        </div>

        <button
          onClick={handleSave}
          disabled={updateConfig.isPending}
          className="mt-4 rounded-md bg-brand-600 px-4 py-1.5 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50"
        >
          {updateConfig.isPending ? 'Saving…' : 'Save Preferences'}
        </button>
        {updateConfig.isSuccess && (
          <span className="ml-3 text-xs text-green-400">Saved</span>
        )}
      </Card>

      {/* Notification History */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">
          Recent Notifications ({history?.length ?? 0})
        </h2>
        <DataTable<NotificationRecord>
          data={history ?? []}
          columns={notifColumns}
          keyField="id"
          pageSize={15}
          emptyMessage="No notifications yet"
        />
      </Card>
    </div>
  );
}
