'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Send } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import { notificationsApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

const CHANNEL_OPTIONS = ['EMAIL', 'SMS', 'PUSH', 'IN_APP'];

export default function NotificationsPage() {
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<any | null>(null);
  const [templateError, setTemplateError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'templates' | 'send' | 'history'>('templates');
  const [sendForm, setSendForm] = useState({ recipientType: 'ALL', channel: 'EMAIL', subject: '', message: '' });
  const [sendError, setSendError] = useState<string | null>(null);
  const [sendSuccess, setSendSuccess] = useState(false);
  const queryClient = useQueryClient();

  const { data: templates, isLoading: templatesLoading } = useQuery({
    queryKey: ['notification-templates'],
    queryFn: notificationsApi.getTemplates,
    enabled: activeTab === 'templates',
  });

  const { data: historyData, isLoading: historyLoading } = useQuery({
    queryKey: ['notification-history'],
    queryFn: () => notificationsApi.getHistory({ take: 50 }),
    enabled: activeTab === 'history',
  });

  const createTemplateMutation = useMutation({
    mutationFn: notificationsApi.createTemplate,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
      closeTemplateModal();
    },
    onError: (e: any) => setTemplateError(e?.response?.data?.message || e?.message || 'Failed to create template'),
  });

  const updateTemplateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => notificationsApi.updateTemplate(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
      closeTemplateModal();
    },
    onError: (e: any) => setTemplateError(e?.response?.data?.message || e?.message || 'Failed to update template'),
  });

  const openCreateModal = () => {
    setEditing(null);
    setTemplateError(null);
    setShowModal(true);
  };

  const openEditModal = (template: any) => {
    setEditing(template);
    setTemplateError(null);
    setShowModal(true);
  };

  const closeTemplateModal = () => {
    setShowModal(false);
    setEditing(null);
    setTemplateError(null);
  };

  const handleTemplateSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setTemplateError(null);
    const fd = new FormData(e.currentTarget);
    const channel = fd.get('channel') as string;
    const subject = (fd.get('subject') as string) || undefined;
    const bodyTemplate = fd.get('bodyTemplate') as string;
    const active = fd.get('active') === 'on';

    if (editing) {
      await updateTemplateMutation.mutateAsync({ id: editing.id, data: { channel, subject, bodyTemplate, active } });
    } else {
      await createTemplateMutation.mutateAsync({ code: fd.get('code') as string, channel, subject, bodyTemplate, active });
    }
  };

  const sendMutation = useMutation({
    mutationFn: notificationsApi.send,
    onSuccess: () => {
      setSendSuccess(true);
      setSendError(null);
      setSendForm({ recipientType: 'ALL', channel: 'EMAIL', subject: '', message: '' });
      setTimeout(() => setSendSuccess(false), 4000);
    },
    onError: (e: any) => setSendError(e?.response?.data?.message || e?.message || 'Failed to send'),
  });

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    setSendError(null);
    await sendMutation.mutateAsync(sendForm);
  };

  const templatesArray = Array.isArray(templates) ? templates : (templates as any)?.items || [];
  const historyArray = Array.isArray(historyData) ? historyData : (historyData as any)?.items || [];

  const templateColumns = [
    { key: 'code', label: 'Code / Event Key', render: (t: any) => <span className="font-mono text-sm font-medium">{t.code}</span> },
    { key: 'channel', label: 'Channel', render: (t: any) => <Badge>{t.channel}</Badge> },
    {
      key: 'subject',
      label: 'Subject / Body',
      render: (t: any) => (
        <span className="text-sm text-muted-foreground truncate max-w-xs block">
          {t.subject ? `${t.subject} — ` : ''}{(t.bodyTemplate || '').replace(/\n/g, ' ') || '—'}
        </span>
      ),
    },
    {
      key: 'active',
      label: 'Status',
      render: (t: any) => (
        <Badge variant="status" status={t.active !== false ? 'CONFIRMED' : 'CANCELLED'}>
          {t.active !== false ? 'Active' : 'Inactive'}
        </Badge>
      ),
    },
    { key: 'createdAt', label: 'Created', render: (t: any) => <span className="text-sm text-muted-foreground">{formatDateTime(t.createdAt)}</span> },
    {
      key: 'actions',
      label: '',
      render: (t: any) => (
        <button onClick={() => openEditModal(t)} className="text-sm font-medium text-primary hover:underline">
          Edit
        </button>
      ),
    },
  ];

  const historyColumns = [
    { key: 'channel', label: 'Channel', render: (n: any) => <Badge>{n.channel || n.type || 'EMAIL'}</Badge> },
    { key: 'title', label: 'Title', render: (n: any) => <span className="font-medium">{n.title || n.subject || '—'}</span> },
    {
      key: 'recipient',
      label: 'Recipient',
      render: (n: any) => <span className="text-sm text-muted-foreground">{n.passenger?.email || n.passenger?.phone || n.recipientEmail || n.recipientPhone || '—'}</span>,
    },
    {
      key: 'status',
      label: 'Status',
      render: (n: any) => (
        <Badge variant="status" status={n.status === 'SENT' || n.isRead !== undefined ? 'CONFIRMED' : 'PENDING'}>
          {n.status || 'SENT'}
        </Badge>
      ),
    },
    { key: 'createdAt', label: 'Sent At', render: (n: any) => <span className="text-sm text-muted-foreground">{formatDateTime(n.createdAt)}</span> },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Notifications</h1>
          <p className="text-muted-foreground">Manage notification templates and send messages</p>
        </div>
        {activeTab === 'templates' && (
          <ActionButton icon={Plus} onClick={openCreateModal}>New Template</ActionButton>
        )}
      </div>

      <div className="flex gap-2 border-b border-border">
        {(['templates', 'send', 'history'] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 font-medium capitalize ${activeTab === tab ? 'border-b-2 border-primary text-primary' : 'text-muted-foreground'}`}
          >
            {tab === 'send' ? 'Send Notification' : tab.charAt(0).toUpperCase() + tab.slice(1)}
          </button>
        ))}
      </div>

      {activeTab === 'templates' && (
        <div className="card">
          <DataTable
            data={templatesArray}
            columns={templateColumns}
            loading={templatesLoading}
            emptyMessage="No notification templates found"
          />
        </div>
      )}

      {activeTab === 'send' && (
        <div className="card">
          {sendSuccess && (
            <div className="mb-4 rounded-lg bg-green-50 dark:bg-green-900/20 p-3 text-sm text-green-800 dark:text-green-200">
              ✓ Notification sent successfully
            </div>
          )}
          <form onSubmit={handleSend} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="label">Recipient Type</label>
                <select className="input" value={sendForm.recipientType} onChange={(e) => setSendForm({ ...sendForm, recipientType: e.target.value })}>
                  <option value="ALL">All Passengers</option>
                  <option value="SPECIFIC">Specific Passenger</option>
                  <option value="BOOKING">Booking Reference</option>
                </select>
              </div>
              <div>
                <label className="label">Channel</label>
                <select className="input" value={sendForm.channel} onChange={(e) => setSendForm({ ...sendForm, channel: e.target.value })}>
                  <option value="EMAIL">Email</option>
                  <option value="SMS">SMS</option>
                  <option value="PUSH">Push Notification</option>
                </select>
              </div>
            </div>
            <div>
              <label className="label">Subject</label>
              <input type="text" className="input" placeholder="Enter subject" value={sendForm.subject} onChange={(e) => setSendForm({ ...sendForm, subject: e.target.value })} required />
            </div>
            <div>
              <label className="label">Message</label>
              <textarea className="input" rows={6} placeholder="Enter message content" value={sendForm.message} onChange={(e) => setSendForm({ ...sendForm, message: e.target.value })} required />
            </div>
            {sendError && <p className="text-sm text-red-600 dark:text-red-400">{sendError}</p>}
            <ActionButton type="submit" icon={Send} loading={sendMutation.isPending}>Send Notification</ActionButton>
          </form>
        </div>
      )}

      {activeTab === 'history' && (
        <div className="card">
          <DataTable
            data={historyArray}
            columns={historyColumns}
            loading={historyLoading}
            emptyMessage="No notification history found"
          />
        </div>
      )}

      <Modal
        isOpen={showModal}
        onClose={closeTemplateModal}
        title={editing ? `Edit Template — ${editing.code}` : 'Create Notification Template'}
      >
        <form onSubmit={handleTemplateSubmit} className="space-y-4">
          <div>
            <label className="label">Code / Event Key {editing ? '' : '*'}</label>
            <input
              type="text"
              name="code"
              className="input font-mono"
              placeholder="e.g., booking.created"
              defaultValue={editing?.code ?? ''}
              required={!editing}
              disabled={!!editing}
            />
            {editing && (
              <p className="mt-1 text-xs text-muted-foreground">Code is the event key and cannot be changed.</p>
            )}
          </div>
          <div>
            <label className="label">Channel *</label>
            <select name="channel" className="input" defaultValue={editing?.channel ?? 'EMAIL'} required>
              {CHANNEL_OPTIONS.map((c) => (
                <option key={c} value={c}>{c}</option>
              ))}
              <option value="SMS,EMAIL">SMS,EMAIL</option>
              <option value="SMS,EMAIL,IN_APP">SMS,EMAIL,IN_APP</option>
            </select>
            <p className="mt-1 text-xs text-muted-foreground">
              One channel, or a comma-separated list (EMAIL, SMS, PUSH, IN_APP).
            </p>
          </div>
          <div>
            <label className="label">Subject</label>
            <input type="text" name="subject" className="input" placeholder="Enter subject" defaultValue={editing?.subject ?? ''} />
          </div>
          <div>
            <label className="label">Body *</label>
            <textarea
              name="bodyTemplate"
              className="input font-mono text-sm"
              rows={8}
              placeholder="Enter template body"
              defaultValue={editing?.bodyTemplate ?? ''}
              required
            />
            <p className="mt-1 text-xs text-muted-foreground">
              Use <code>{'{{variable}}'}</code> placeholders (e.g. <code>{'{{passengerName}}'}</code>, <code>{'{{bookingRef}}'}</code>) — they are filled in when the notification is sent.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <input type="checkbox" name="active" id="template-active" defaultChecked={editing ? editing.active !== false : true} />
            <label htmlFor="template-active" className="text-sm">Active</label>
          </div>
          {templateError && <p className="text-sm text-red-600 dark:text-red-400">{templateError}</p>}
          <div className="flex justify-end gap-2">
            <ActionButton type="button" variant="secondary" onClick={closeTemplateModal}>Cancel</ActionButton>
            <ActionButton type="submit" loading={createTemplateMutation.isPending || updateTemplateMutation.isPending}>
              {editing ? 'Save Changes' : 'Create Template'}
            </ActionButton>
          </div>
        </form>
      </Modal>
    </div>
  );
}
