import React, { useState, useEffect } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';

function StatCard({ label, value, icon, active, onClick }: { label: string; value: string | number; icon: string; active?: boolean; onClick?: () => void }) {
  return (
    <button onClick={onClick}
      className={`bg-[#141414] border rounded-xl p-5 text-left transition-colors w-full ${active ? 'border-[#00FF6A]' : 'border-[#333] hover:border-[#555]'}`}>
      <div className="flex items-center justify-between mb-2">
        <span className="text-[#999] text-sm">{label}</span>
        <span className="text-lg">{icon}</span>
      </div>
      <div className={`text-2xl font-bold ${active ? 'text-[#00FF6A]' : 'text-[#F5F5F5]'}`}>{value}</div>
    </button>
  );
}

function SubscribersContent() {
  const { token } = useAuth();
  const [subscribers, setSubscribers] = useState<any[]>([]);
  const [totals, setTotals] = useState<any>({});
  const [filter, setFilter] = useState('all');
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState<any>(null);
  const [userDetail, setUserDetail] = useState<any>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };

  const load = (f: string) => {
    setLoading(true);
    setFilter(f);
    fetch(`/api/admin/subscribers?filter=${f}`, { headers })
      .then(r => r.json())
      .then(res => {
        setSubscribers(res.data || []);
        setTotals(res.totals || {});
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => { load('all'); }, []);

  const loadDetail = (user: any) => {
    setSelectedUser(user);
    setDetailLoading(true);
    fetch('/api/admin/subscribers', {
      method: 'POST',
      headers,
      body: JSON.stringify({ userId: user.id }),
    })
      .then(r => r.json())
      .then(res => setUserDetail(res))
      .finally(() => setDetailLoading(false));
  };

  return (
    <AdminLayout title="Subscribers">
      {/* Totals */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <StatCard label="Totaal" value={totals.total || 0} icon="👥" active={filter === 'all'} onClick={() => load('all')} />
        <StatCard label="Geverifieerd" value={totals.verified || 0} icon="✅" active={filter === 'verified'} onClick={() => load('verified')} />
        <StatCard label="Niet geverifieerd" value={totals.unverified || 0} icon="⏳" active={filter === 'unverified'} onClick={() => load('unverified')} />
        <StatCard label="Uitgeschreven" value={totals.unsubscribed || 0} icon="🚫" active={filter === 'unsubscribed'} onClick={() => load('unsubscribed')} />
      </div>

      <div className="flex gap-6">
        {/* Subscribers list */}
        <div className={`${selectedUser ? 'w-1/2' : 'w-full'} transition-all`}>
          <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden">
            {loading ? (
              <div className="flex items-center justify-center py-20">
                <div className="w-8 h-8 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
              </div>
            ) : subscribers.length === 0 ? (
              <div className="text-[#666] text-center py-20">Geen subscribers gevonden</div>
            ) : (
              <table className="w-full text-sm">
                <thead className="text-[#999] text-left bg-[#0F0F0F]">
                  <tr>
                    <th className="p-3">Email</th>
                    <th className="p-3 text-center">Status</th>
                    <th className="p-3 text-center">Watchlist</th>
                    <th className="p-3 text-center">Alerts</th>
                    <th className="p-3">Aangemeld</th>
                  </tr>
                </thead>
                <tbody>
                  {subscribers.map((s: any) => (
                    <tr key={s.id}
                      onClick={() => loadDetail(s)}
                      className={`border-t border-[#222] cursor-pointer transition-colors ${selectedUser?.id === s.id ? 'bg-[#00FF6A]/5' : 'hover:bg-[#1A1A1A]'}`}>
                      <td className="p-3 text-[#F5F5F5] font-medium">{s.email}</td>
                      <td className="p-3 text-center">
                        {s.unsubscribed ? (
                          <span className="bg-[#FF3B3B]/10 text-[#FF3B3B] px-2 py-0.5 rounded text-xs">Uitgeschreven</span>
                        ) : s.email_verified ? (
                          <span className="bg-[#00FF6A]/10 text-[#00FF6A] px-2 py-0.5 rounded text-xs">Geverifieerd</span>
                        ) : (
                          <span className="bg-[#FFB800]/10 text-[#FFB800] px-2 py-0.5 rounded text-xs">Onbevestigd</span>
                        )}
                      </td>
                      <td className="p-3 text-center text-[#999]">{s.watchlist_count}</td>
                      <td className="p-3 text-center text-[#999]">{s.alert_count}</td>
                      <td className="p-3 text-[#999] text-xs">{new Date(s.created_at).toLocaleDateString('nl-NL')}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* Detail panel */}
        {selectedUser && (
          <div className="w-1/2">
            <div className="bg-[#141414] border border-[#333] rounded-xl p-5 sticky top-4">
              <div className="flex items-center justify-between mb-4">
                <div>
                  <h3 className="text-[#F5F5F5] font-bold">{selectedUser.email}</h3>
                  <p className="text-[#999] text-xs mt-1">
                    Lid sinds {new Date(selectedUser.created_at).toLocaleDateString('nl-NL')}
                  </p>
                </div>
                <button onClick={() => { setSelectedUser(null); setUserDetail(null); }}
                  className="text-[#999] hover:text-white text-lg">✕</button>
              </div>

              {detailLoading ? (
                <div className="flex items-center justify-center py-10">
                  <div className="w-6 h-6 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
                </div>
              ) : userDetail ? (
                <div className="space-y-6">
                  {/* Email History */}
                  {userDetail.emailHistory?.length > 0 && (
                    <div>
                      <h4 className="text-[#999] text-xs font-medium uppercase tracking-wider mb-2">Email Geschiedenis</h4>
                      <div className="space-y-1">
                        {userDetail.emailHistory.map((e: any, i: number) => (
                          <div key={i} className="flex justify-between text-sm">
                            <span className="text-[#F5F5F5]">{e.email_type}</span>
                            <span className="text-[#999]">{e.count}× (laatst: {new Date(e.last_sent).toLocaleDateString('nl-NL')})</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Price Alerts */}
                  {userDetail.alerts?.length > 0 && (
                    <div>
                      <h4 className="text-[#999] text-xs font-medium uppercase tracking-wider mb-2">
                        Prijsalerts ({userDetail.alerts.length})
                      </h4>
                      <div className="space-y-2">
                        {userDetail.alerts.map((a: any, i: number) => (
                          <div key={i} className="flex items-center gap-3 bg-[#0A0A0A] rounded-lg p-3">
                            <div className="flex-1 min-w-0">
                              <div className="text-[#F5F5F5] text-sm truncate">{a.name}</div>
                              <div className="text-[#666] text-xs">{a.brand}</div>
                            </div>
                            <div className="text-right">
                              <div className="text-[#FFB800] text-sm font-medium">Target: €{parseFloat(a.target_price).toFixed(2)}</div>
                              {a.current_price && (
                                <div className={`text-xs ${parseFloat(a.current_price) <= parseFloat(a.target_price) ? 'text-[#00FF6A]' : 'text-[#999]'}`}>
                                  Nu: €{parseFloat(a.current_price).toFixed(2)}
                                </div>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Watchlist */}
                  {userDetail.watchlist?.length > 0 && (
                    <div>
                      <h4 className="text-[#999] text-xs font-medium uppercase tracking-wider mb-2">
                        Watchlist ({userDetail.watchlist.length})
                      </h4>
                      <div className="space-y-2 max-h-[300px] overflow-auto">
                        {userDetail.watchlist.map((w: any, i: number) => (
                          <div key={i} className="flex items-center gap-3 bg-[#0A0A0A] rounded-lg p-2">
                            {w.image_url && (
                              <img src={w.image_url} alt="" className="w-10 h-10 rounded bg-white object-contain flex-shrink-0" />
                            )}
                            <div className="flex-1 min-w-0">
                              <div className="text-[#F5F5F5] text-sm truncate">{w.name}</div>
                              <div className="text-[#666] text-xs">{w.brand}</div>
                            </div>
                            {w.target_price && (
                              <span className="text-[#FFB800] text-xs">🔔 €{parseFloat(w.target_price).toFixed(2)}</span>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {!userDetail.watchlist?.length && !userDetail.alerts?.length && (
                    <div className="text-[#666] text-center py-10">Geen watchlist of alerts</div>
                  )}
                </div>
              ) : null}
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}

export default function Subscribers() {
  return <AuthProvider><AuthGuard><SubscribersContent /></AuthGuard></AuthProvider>;
}
