'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  Mail,
  Send,
  FileText,
  BarChart3,
  Plus,
  Search,
  MoreHorizontal,
  CheckCircle,
  Clock,
  XCircle,
  Eye,
  AlertTriangle,
  ArrowRight,
} from 'lucide-react';
import { api } from '@/lib/api';
import { TemplateDialog } from '@/components/email/template-dialog';
import { SendTestDialog } from '@/components/email/send-test-dialog';
import { AlertDialog } from '@/components/ui/alert-dialog';

type EmailType = 'WELCOME' | 'TRAINING_REMINDER' | 'MEMBERSHIP_EXPIRING' | 'PROMO' | 'BIRTHDAY';
type EmailStatus = 'PENDING' | 'SENT' | 'DELIVERED' | 'OPENED' | 'CLICKED' | 'BOUNCED' | 'FAILED';

type EmailTemplate = {
  id: string;
  type: EmailType;
  subject: string;
  bodyHtml: string;
  bodyText?: string;
  variables: string[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
};

type EmailLog = {
  id: string;
  recipientEmail: string;
  subject: string;
  type: EmailType;
  status: EmailStatus;
  errorMessage?: string;
  sentAt?: string;
  deliveredAt?: string;
  openedAt?: string;
  createdAt: string;
};

type EmailStats = {
  total: number;
  sent: number;
  delivered: number;
  opened: number;
  failed: number;
};

type LogsResponse = {
  data: EmailLog[];
  nextCursor: string | null;
  hasMore: boolean;
};

type Tab = 'templates' | 'logs' | 'stats';

const EMAIL_TYPE_LABELS: Record<EmailType, string> = {
  WELCOME: 'Приветствие',
  TRAINING_REMINDER: 'Напоминание о тренировке',
  MEMBERSHIP_EXPIRING: 'Истечение абонемента',
  PROMO: 'Промо-акция',
  BIRTHDAY: 'День рождения',
};

const STATUS_CONFIG: Record<EmailStatus, { label: string; className: string; icon: typeof CheckCircle }> = {
  PENDING: { label: 'Ожидает', className: 'text-muted', icon: Clock },
  SENT: { label: 'Отправлено', className: 'text-blue-600', icon: Send },
  DELIVERED: { label: 'Доставлено', className: 'text-success', icon: CheckCircle },
  OPENED: { label: 'Прочитано', className: 'text-green-700', icon: Eye },
  CLICKED: { label: 'Переход', className: 'text-primary', icon: ArrowRight },
  BOUNCED: { label: 'Отклонено', className: 'text-warning', icon: AlertTriangle },
  FAILED: { label: 'Ошибка', className: 'text-error', icon: XCircle },
};

export default function EmailPage(): React.JSX.Element {
  const [tab, setTab] = useState<Tab>('templates');

  // Templates state
  const [templates, setTemplates] = useState<EmailTemplate[]>([]);
  const [templatesLoading, setTemplatesLoading] = useState(true);

  // Logs state
  const [logs, setLogs] = useState<EmailLog[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [logSearch, setLogSearch] = useState('');
  const [logStatusFilter, setLogStatusFilter] = useState<EmailStatus | ''>('');

  // Stats state
  const [stats, setStats] = useState<EmailStats | null>(null);
  const [statsLoading, setStatsLoading] = useState(false);

  // Global
  const [error, setError] = useState<string | null>(null);

  // Dialogs
  const [showTemplateDialog, setShowTemplateDialog] = useState(false);
  const [editTemplate, setEditTemplate] = useState<EmailTemplate | null>(null);
  const [deleteTemplate, setDeleteTemplate] = useState<EmailTemplate | null>(null);
  const [showSendTest, setShowSendTest] = useState(false);
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);

  const loadTemplates = useCallback(() => {
    setTemplatesLoading(true);
    api.get<EmailTemplate[]>('/email/templates')
      .then((res) => {
        setTemplates(Array.isArray(res) ? res : []);
        setError(null);
      })
      .catch((err) => {
        setTemplates([]);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить шаблоны');
      })
      .finally(() => setTemplatesLoading(false));
  }, []);

  const loadLogs = useCallback(() => {
    setLogsLoading(true);
    const params = new URLSearchParams();
    params.set('limit', '50');
    if (logStatusFilter) params.set('status', logStatusFilter);
    api.get<LogsResponse>(`/email/logs?${params.toString()}`)
      .then((res) => {
        setLogs(res.data ?? []);
        setError(null);
      })
      .catch((err) => {
        setLogs([]);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить логи');
      })
      .finally(() => setLogsLoading(false));
  }, [logStatusFilter]);

  const loadStats = useCallback(() => {
    setStatsLoading(true);
    api.get<EmailStats>('/email/stats')
      .then((res) => {
        setStats(res);
        setError(null);
      })
      .catch((err) => {
        setStats(null);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить статистику');
      })
      .finally(() => setStatsLoading(false));
  }, []);

  useEffect(() => {
    loadTemplates();
  }, [loadTemplates]);

  useEffect(() => {
    if (tab === 'logs') loadLogs();
  }, [tab, loadLogs]);

  useEffect(() => {
    if (tab === 'stats') loadStats();
  }, [tab, loadStats]);

  const handleDeleteTemplate = async () => {
    if (!deleteTemplate) return;
    try {
      await api.delete(`/email/templates/${deleteTemplate.type}`);
      setDeleteTemplate(null);
      loadTemplates();
    } catch {
      // handled in alert dialog
    }
  };

  const filteredLogs = logs.filter(
    (log) =>
      log.recipientEmail.toLowerCase().includes(logSearch.toLowerCase()) ||
      log.subject.toLowerCase().includes(logSearch.toLowerCase())
  );

  const tabs: { id: Tab; label: string; icon: typeof Mail }[] = [
    { id: 'templates', label: 'Шаблоны', icon: FileText },
    { id: 'logs', label: 'Логи отправок', icon: Mail },
    { id: 'stats', label: 'Статистика', icon: BarChart3 },
  ];

  if (templatesLoading && tab === 'templates') {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error && templates.length === 0 && logs.length === 0 && !stats) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={() => { loadTemplates(); loadLogs(); loadStats(); }}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Email-рассылки</h1>
          <p className="text-sm text-muted mt-1">
            Управление шаблонами писем, отправка и аналитика
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowSendTest(true)}
            className="flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
          >
            <Send className="h-4 w-4" />
            Тестовое письмо
          </button>
          <button
            onClick={() => { setEditTemplate(null); setShowTemplateDialog(true); }}
            className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-4 w-4" />
            Новый шаблон
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-6 bg-gray-100 rounded-xl p-1 w-fit">
        {tabs.map((t) => {
          const Icon = t.icon;
          return (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                tab === t.id
                  ? 'bg-white text-gray-900 shadow-sm'
                  : 'text-gray-500 hover:text-gray-700'
              }`}
            >
              <Icon className="h-4 w-4" />
              {t.label}
            </button>
          );
        })}
      </div>

      {/* Templates Tab */}
      {tab === 'templates' && (
        <div className="space-y-4">
          {templates.length === 0 ? (
            <div className="text-center py-12 bg-card rounded-xl border border-border">
              <Mail className="h-12 w-12 text-muted mx-auto mb-3" />
              <p className="text-sm text-muted mb-4">
                Шаблонов ещё нет. Создайте первый шаблон для email-рассылок.
              </p>
              <button
                onClick={() => { setEditTemplate(null); setShowTemplateDialog(true); }}
                className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
              >
                Создать шаблон
              </button>
            </div>
          ) : (
            templates.map((template) => {
              const StatusIcon = template.isActive ? CheckCircle : XCircle;
              return (
                <div
                  key={template.id}
                  className="bg-card rounded-xl p-6 shadow-sm border border-border"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-4">
                      <div className="bg-orange-50 text-primary p-3 rounded-lg">
                        <FileText className="h-5 w-5" />
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <h3 className="text-base font-semibold text-gray-900">
                            {EMAIL_TYPE_LABELS[template.type] ?? template.type}
                          </h3>
                          <span className={`inline-flex items-center gap-1 text-xs font-medium ${
                            template.isActive ? 'text-success' : 'text-muted'
                          }`}>
                            <StatusIcon className="h-3.5 w-3.5" />
                            {template.isActive ? 'Активен' : 'Выключен'}
                          </span>
                        </div>
                        <p className="text-sm text-gray-600 mt-1">
                          Тема: {template.subject}
                        </p>
                        {template.variables.length > 0 && (
                          <div className="flex flex-wrap gap-1.5 mt-2">
                            {template.variables.map((v) => (
                              <span
                                key={v}
                                className="bg-blue-50 text-blue-700 px-2 py-0.5 rounded text-xs font-mono"
                              >
                                {`{{${v}}}`}
                              </span>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                    <div className="relative">
                      <button
                        onClick={() => setOpenMenuId(openMenuId === template.id ? null : template.id)}
                        className="p-1 rounded hover:bg-gray-100"
                      >
                        <MoreHorizontal className="h-4 w-4 text-muted" />
                      </button>
                      {openMenuId === template.id && (
                        <div className="absolute right-0 top-full mt-1 w-44 bg-white border border-border rounded-xl shadow-lg z-20">
                          <button
                            onClick={() => {
                              setOpenMenuId(null);
                              setEditTemplate(template);
                              setShowTemplateDialog(true);
                            }}
                            className="w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 rounded-t-xl transition-colors"
                          >
                            Редактировать
                          </button>
                          <button
                            onClick={() => {
                              setOpenMenuId(null);
                              setDeleteTemplate(template);
                            }}
                            className="w-full text-left px-4 py-2.5 text-sm text-error hover:bg-red-50 rounded-b-xl transition-colors"
                          >
                            Удалить
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      )}

      {/* Logs Tab */}
      {tab === 'logs' && (
        <div className="bg-card rounded-xl shadow-sm border border-border">
          <div className="p-4 border-b border-border flex items-center gap-4">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
              <input
                type="text"
                placeholder="Поиск по email или теме..."
                value={logSearch}
                onChange={(e) => setLogSearch(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
              />
            </div>
            <select
              value={logStatusFilter}
              onChange={(e) => setLogStatusFilter(e.target.value as EmailStatus | '')}
              className="px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
            >
              <option value="">Все статусы</option>
              {Object.entries(STATUS_CONFIG).map(([key, val]) => (
                <option key={key} value={key}>{val.label}</option>
              ))}
            </select>
          </div>

          {logsLoading ? (
            <div className="flex items-center justify-center h-32">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-border">
                      <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Получатель</th>
                      <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Тема</th>
                      <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Тип</th>
                      <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Статус</th>
                      <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Дата</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredLogs.map((log) => {
                      const sc = STATUS_CONFIG[log.status];
                      const StatusIcon = sc.icon;
                      return (
                        <tr key={log.id} className="border-b border-border last:border-0 hover:bg-gray-50 transition-colors">
                          <td className="px-6 py-4 text-sm font-medium text-gray-900 font-mono">
                            {log.recipientEmail}
                          </td>
                          <td className="px-6 py-4 text-sm text-gray-600 max-w-xs truncate">
                            {log.subject}
                          </td>
                          <td className="px-6 py-4">
                            <span className="bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-full text-xs font-medium">
                              {EMAIL_TYPE_LABELS[log.type] ?? log.type}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`inline-flex items-center gap-1 text-xs font-medium ${sc.className}`}>
                              <StatusIcon className="h-3.5 w-3.5" />
                              {sc.label}
                            </span>
                          </td>
                          <td className="px-6 py-4 text-sm text-gray-600">
                            {log.sentAt
                              ? new Date(log.sentAt).toLocaleString('ru-RU')
                              : new Date(log.createdAt).toLocaleString('ru-RU')}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {filteredLogs.length === 0 && (
                <div className="text-center py-12 text-muted text-sm">
                  Нет записей о отправках
                </div>
              )}

              <div className="px-6 py-3 border-t border-border text-sm text-muted">
                Показано {filteredLogs.length} записей
              </div>
            </>
          )}
        </div>
      )}

      {/* Stats Tab */}
      {tab === 'stats' && (
        <div>
          {statsLoading ? (
            <div className="flex items-center justify-center h-32">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
            </div>
          ) : stats ? (
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {[
                { label: 'Всего', value: stats.total, icon: Mail, color: 'text-gray-900' },
                { label: 'Отправлено', value: stats.sent, icon: Send, color: 'text-blue-600' },
                { label: 'Доставлено', value: stats.delivered, icon: CheckCircle, color: 'text-success' },
                { label: 'Прочитано', value: stats.opened, icon: Eye, color: 'text-green-700' },
                { label: 'Ошибки', value: stats.failed, icon: XCircle, color: 'text-error' },
              ].map((stat) => {
                const Icon = stat.icon;
                return (
                  <div
                    key={stat.label}
                    className="bg-card rounded-xl p-6 shadow-sm border border-border"
                  >
                    <div className="flex items-center gap-2 mb-2">
                      <Icon className={`h-4 w-4 ${stat.color}`} />
                      <span className="text-xs font-medium text-muted uppercase tracking-wider">
                        {stat.label}
                      </span>
                    </div>
                    <p className={`text-2xl font-bold ${stat.color}`}>
                      {stat.value.toLocaleString('ru-RU')}
                    </p>
                    {stat.label === 'Доставлено' && stats.total > 0 && (
                      <p className="text-xs text-muted mt-1">
                        {Math.round((stats.delivered / stats.total) * 100)}% от всех
                      </p>
                    )}
                    {stat.label === 'Прочитано' && stats.delivered > 0 && (
                      <p className="text-xs text-muted mt-1">
                        {Math.round((stats.opened / stats.delivered) * 100)}% open rate
                      </p>
                    )}
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-center py-12 text-muted text-sm">
              Нет данных по статистике
            </div>
          )}
        </div>
      )}

      {/* Dialogs */}
      <TemplateDialog
        open={showTemplateDialog}
        onClose={() => { setShowTemplateDialog(false); setEditTemplate(null); }}
        onSaved={() => { setShowTemplateDialog(false); setEditTemplate(null); loadTemplates(); }}
        template={editTemplate}
      />

      <SendTestDialog
        open={showSendTest}
        onClose={() => setShowSendTest(false)}
        templates={templates}
      />

      <AlertDialog
        open={deleteTemplate !== null}
        onClose={() => setDeleteTemplate(null)}
        onConfirm={handleDeleteTemplate}
        title="Удалить шаблон"
        description={`Шаблон «${deleteTemplate ? EMAIL_TYPE_LABELS[deleteTemplate.type] : ''}» будет удалён безвозвратно. Продолжить?`}
        confirmLabel="Удалить"
        variant="danger"
      />
    </div>
  );
}
