'use client';

import React, { useState, useEffect, useCallback } from 'react';

interface Subscriber {
  id: number;
  email: string;
  isActive: boolean;
  subscribedAt: string;
}

interface SubscribersResponse {
  subscribers: Subscriber[];
  totalCount: number;
  totalPages: number;
  currentPage: number;
}

interface SubscribersModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const DeleteConfirmRow = ({ 
  email, 
  onConfirm, 
  onCancel, 
  isDeleting 
}: { 
  email: string; 
  onConfirm: () => void; 
  onCancel: () => void;
  isDeleting: boolean;
}) => (
  <div className="bg-red-50 p-4 rounded-lg flex items-center justify-between border border-red-100 animate-in slide-in-from-top-2 duration-200">
    <div className="flex items-center gap-3">
      <span className="text-red-600 text-xl">⚠️</span>
      <p className="text-sm text-red-800">
        Are you sure you want to delete <span className="font-bold">{email}</span>?
      </p>
    </div>
    <div className="flex gap-2">
      <button 
        onClick={onCancel}
        className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50"
      >
        Cancel
      </button>
      <button 
        onClick={onConfirm}
        disabled={isDeleting}
        className="px-3 py-1.5 text-xs font-medium text-white bg-red-600 rounded-md hover:bg-red-700 disabled:opacity-50 flex items-center gap-2"
      >
        {isDeleting && (
          <svg className="animate-spin h-3 w-3 text-white" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
          </svg>
        )}
        Yes, Delete
      </button>
    </div>
  </div>
);

export const SubscribersModal = ({ isOpen, onClose }: SubscribersModalProps) => {
  const [data, setData] = useState<SubscribersResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const fetchSubscribers = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/newsletter/subscribers?page=${page}&limit=10`);
      if (!res.ok) throw new Error('Failed to fetch subscribers');
      const json = await res.json();
      setData(json);
      setError(null);
    } catch (err) {
      setError('Failed to load subscribers');
    } finally {
      setLoading(false);
    }
  }, [page]);

  useEffect(() => {
    if (isOpen) {
      fetchSubscribers();
    }
  }, [isOpen, page, fetchSubscribers]);

  const handleDelete = async (id: number) => {
    setDeletingId(id);
    try {
      const res = await fetch(`/api/newsletter/subscribers/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setConfirmDeleteId(null);
        // If it was the last item on the page and not the first page, go back
        if (data?.subscribers.length === 1 && page > 1) {
          setPage(page - 1);
        } else {
          fetchSubscribers();
        }
      } else {
        alert('Failed to delete subscriber');
      }
    } catch (err) {
      alert('Error deleting subscriber');
    } finally {
      setDeletingId(null);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('ja-JP', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[300000] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      
      <div className="relative z-[300001] bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden animate-in fade-in zoom-in duration-200">
        {/* Header */}
        <div className="px-6 py-4 border-b flex items-center justify-between bg-gray-50/50">
          <div className="flex items-center gap-3">
            <span className="text-2xl">📧</span>
            <div>
              <h2 className="text-xl font-bold text-gray-800">Newsletter Subscribers</h2>
              <p className="text-xs text-gray-500 font-medium">Manage your mailing list</p>
            </div>
          </div>
          <button 
            onClick={onClose}
            className="p-2 hover:bg-gray-200 rounded-full transition-colors text-gray-400 hover:text-gray-600"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {error && (
            <div className="bg-red-50 text-red-600 p-4 rounded-xl mb-6 text-sm flex items-center gap-3">
              <span>⚠️</span> {error}
            </div>
          )}

          {loading && !data ? (
            <div className="flex flex-col items-center justify-center py-20 gap-4">
              <div className="w-10 h-10 border-4 border-green-200 border-t-green-600 rounded-full animate-spin"></div>
              <p className="text-gray-500 text-sm animate-pulse">Loading subscribers...</p>
            </div>
          ) : data?.subscribers.length === 0 ? (
            <div className="text-center py-20">
              <div className="text-6xl mb-4">📭</div>
              <h3 className="text-lg font-bold text-gray-800">No subscribers yet</h3>
              <p className="text-gray-500 text-sm">When users sign up via the popup, they will appear here.</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left border-separate border-spacing-y-2">
                <thead>
                  <tr className="text-gray-400 text-xs uppercase tracking-wider">
                    <th className="px-4 py-2 font-semibold">Email Address</th>
                    <th className="px-4 py-2 font-semibold">Status</th>
                    <th className="px-4 py-2 font-semibold">Subscribed Date</th>
                    <th className="px-4 py-2 font-semibold text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {data?.subscribers.map((sub) => (
                    <React.Fragment key={sub.id}>
                      <tr className={`group bg-gray-50/50 hover:bg-gray-50 transition-colors ${confirmDeleteId === sub.id ? 'ring-2 ring-red-200' : ''}`}>
                        <td className="px-4 py-4 rounded-l-xl">
                          <span className="text-sm font-medium text-gray-700">{sub.email}</span>
                        </td>
                        <td className="px-4 py-4">
                          <span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold ${
                            sub.isActive ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                          }`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${sub.isActive ? 'bg-green-500' : 'bg-gray-400'}`}></span>
                            {sub.isActive ? 'ACTIVE' : 'UNSUBSCRIBED'}
                          </span>
                        </td>
                        <td className="px-4 py-4 text-xs text-gray-500 tabular-nums">
                          {formatDate(sub.subscribedAt)}
                        </td>
                        <td className="px-4 py-4 text-right rounded-r-xl">
                          <button 
                            onClick={() => setConfirmDeleteId(confirmDeleteId === sub.id ? null : sub.id)}
                            className={`p-2 rounded-lg transition-all ${
                              confirmDeleteId === sub.id ? 'bg-red-600 text-white' : 'hover:bg-red-100 text-gray-400 hover:text-red-600'
                            }`}
                            title="Delete Subscriber"
                          >
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M3 6h18"></path>
                              <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
                              <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
                            </svg>
                          </button>
                        </td>
                      </tr>
                      {confirmDeleteId === sub.id && (
                        <tr>
                          <td colSpan={4} className="px-2 pb-2">
                            <DeleteConfirmRow
                              email={sub.email}
                              onConfirm={() => handleDelete(sub.id)}
                              onCancel={() => setConfirmDeleteId(null)}
                              isDeleting={deletingId === sub.id}
                            />
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Footer / Pagination */}
        {data && data.totalPages > 1 && (
          <div className="px-6 py-4 border-t bg-gray-50/50 flex items-center justify-between">
            <p className="text-xs text-gray-500">
              Showing page {data.currentPage} of {data.totalPages} ({data.totalCount} total)
            </p>
            <div className="flex gap-2">
              <button
                disabled={page === 1 || loading}
                onClick={() => setPage(p => p - 1)}
                className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-30 disabled:hover:bg-white transition-all"
              >
                Previous
              </button>
              <button
                disabled={page >= data.totalPages || loading}
                onClick={() => setPage(p => p + 1)}
                className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-30 disabled:hover:bg-white transition-all"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
