'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useGameStore, type PlayerGauges } from '@/stores/gameStore';
import { t } from '@/lib/i18n';
import { Bell, Settings, MessageSquare } from 'lucide-react';
import { LanguageSelector } from '../ui/LanguageSelector';
import { GaugeBar } from '../ui/GaugeBar';
import { GAUGE_ICONS } from '../ui/GameIcons';
import { apiFetch } from '@/lib/api';

/** Typed gauge configuration — no `as any` needed */
// Phase 8 v2 (2026-05-01) — storeKey peut désigner :
//   • Une clé de PlayerGauges (player_gauges table) — chaleur, conscience, etc.
//   • OU 'physical_health' qui est résolu depuis PlayerHealth.physical_health
//     (player_health table) via branch ternaire dans le render.
type GaugeStoreKey = keyof PlayerGauges | 'physical_health';

interface GaugeConfig {
  storeKey: GaugeStoreKey;
  color: string;
}

const GAUGE_CONFIG: GaugeConfig[] = [
  { storeKey: 'fortune', color: '#d4a843' },
  { storeKey: 'pouvoir', color: '#e63946' },
  { storeKey: 'chaleur', color: '#f97316' },
  { storeKey: 'conscience', color: '#8b5cf6' },
  { storeKey: 'respect', color: '#d4a843' },
  { storeKey: 'social', color: '#06b6d4' },
  { storeKey: 'popularite', color: '#eab308' },
  { storeKey: 'instabilite', color: '#ef4444' },
  { storeKey: 'influence', color: '#22c55e' },
  { storeKey: 'ecologie', color: '#16a34a' },
  // Phase 8 v2 (2026-05-01) — storeKey 'physical_health' lu depuis health.*
  // (et plus depuis gauges.*) via le branch ternaire dans la boucle render.
  // Source unique : PlayerHealth.physical_health (player_health table).
  { storeKey: 'physical_health', color: '#ec4899' },
];

interface NotificationItem {
  id: string;
  type: string;
  title: string;
  message: string;
  is_read: boolean;
  created_at: string;
}

export function Header() {
  const { player, gauges, health, isAuthenticated } = useGameStore();
  const router = useRouter();
  const [showNotifications, setShowNotifications] = useState(false);
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [notifLoading, setNotifLoading] = useState(false);
  const [time, setTime] = useState('');
  const [showMessages, setShowMessages] = useState(false);
  const [messageTab, setMessageTab] = useState<'perso' | 'equipe'>('perso');
  const [messages, setMessages] = useState<{ id: string; sender_name: string; content: string; is_read: boolean; created_at: string }[]>([]);
  const [msgLoading, setMsgLoading] = useState(false);
  const [hasGang, setHasGang] = useState(false);
  const [teamMessages, setTeamMessages] = useState<any[]>([]);
  const [teamLoading, setTeamLoading] = useState(false);
  const [proximityUnread, setProximityUnread] = useState(0);
  const [teamUnread, setTeamUnread] = useState(0);
  const notifRef = useRef<HTMLDivElement>(null);
  const msgRef = useRef<HTMLDivElement>(null);

  // Horloge temps réel
  useEffect(() => {
    const update = () => setTime(new Date().toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }));
    update();
    const i = setInterval(update, 60000);
    return () => clearInterval(i);
  }, []);

  const loadNotifications = useCallback(async () => {
    if (!player?.id) return;
    setNotifLoading(true);
    try {
      const data = await apiFetch<NotificationItem[]>(`/api/player/${player.id}/notifications`);
      setNotifications(Array.isArray(data) ? data : []);
    } catch {
    } finally {
      setNotifLoading(false);
    }
  }, [player?.id]);

  useEffect(() => {
    if (showNotifications) {
      loadNotifications();
    }
  }, [showNotifications, loadNotifications]);

  const markAsRead = async (notifId: string) => {
    if (!player?.id) return;
    try {
      await apiFetch(`/api/player/${player.id}/notifications/${notifId}/read`, { method: 'PUT' });
      setNotifications((prev) => prev.map((n) => (n.id === notifId ? { ...n, is_read: true } : n)));
    } catch {
    }
  };

  // Fermer le dropdown notifications au clic extérieur
  useEffect(() => {
    if (!showNotifications) return;
    const handleClick = (e: MouseEvent) => {
      if (notifRef.current && !notifRef.current.contains(e.target as Node)) {
        setShowNotifications(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showNotifications]);

  const unreadCount = notifications.filter((n) => !n.is_read).length;

  // Messagerie : fetch messages
  useEffect(() => {
    if (!player?.id || !showMessages) return;
    setMsgLoading(true);
    apiFetch<any>(`/api/player/${player.id}/messages`)
      .then((res) => setMessages(Array.isArray(res) ? res : res?.data ?? []))
      .catch(() => setMessages([]))
      .finally(() => setMsgLoading(false));
  }, [player?.id, showMessages]);

  useEffect(() => {
    if (!isAuthenticated) {
      setHasGang(false);
      return;
    }
    apiFetch<any>('/api/gang/mine')
      .then((g) => setHasGang(!!g))
      .catch(() => setHasGang(false));
  }, [isAuthenticated]);

  useEffect(() => {
    if (!showMessages || messageTab !== 'equipe' || !hasGang) return;
    setTeamLoading(true);
    apiFetch<any>('/api/chat/messages?channel=gang&limit=30')
      .then((res) => setTeamMessages(Array.isArray(res) ? res : res?.messages ?? res?.data ?? []))
      .catch(() => setTeamMessages([]))
      .finally(() => setTeamLoading(false));
  }, [showMessages, messageTab, hasGang]);

  useEffect(() => {
    if (!showMessages || messageTab !== 'equipe' || !hasGang) return;
    localStorage.setItem('ol_chat_last_seen_gang', String(Date.now()));
    setTeamUnread(0);
  }, [showMessages, messageTab, hasGang]);

  // Fermer le dropdown messages au clic exterieur
  useEffect(() => {
    if (!showMessages) return;
    const handleClick = (e: MouseEvent) => {
      if (msgRef.current && !msgRef.current.contains(e.target as Node)) {
        setShowMessages(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showMessages]);

  const unreadMessages = messages.filter((m) => !m.is_read).length;
  const totalMessageBadge = unreadMessages + proximityUnread + teamUnread;

  useEffect(() => {
    if (!player?.id || !isAuthenticated) return;

    let cancelled = false;

    const computeUnread = (list: any[], lastSeenKey: string) => {
      const lastSeen = Number(localStorage.getItem(lastSeenKey) || 0);
      const unread = list.filter((m) => {
        const createdAt = new Date(m.created_at).getTime();
        if (!Number.isFinite(createdAt)) return false;
        if (createdAt <= lastSeen) return false;
        if (m.sender_id && m.sender_id === player.id) return false;
        return true;
      }).length;
      return unread;
    };

    const poll = async () => {
      try {
        const proximity = await apiFetch<any>('/api/chat/messages?channel=proximity&limit=20').catch(() => []);
        const proximityList = Array.isArray(proximity) ? proximity : proximity?.messages ?? proximity?.data ?? [];
        const pUnread = computeUnread(proximityList, 'ol_chat_last_seen_proximity');
        if (!cancelled) setProximityUnread(pUnread);
      } catch {
      }

      if (!hasGang) {
        if (!cancelled) setTeamUnread(0);
        return;
      }

      try {
        const gang = await apiFetch<any>('/api/chat/messages?channel=gang&limit=20').catch(() => []);
        const gangList = Array.isArray(gang) ? gang : gang?.messages ?? gang?.data ?? [];
        const gUnread = computeUnread(gangList, 'ol_chat_last_seen_gang');
        if (!cancelled) setTeamUnread(gUnread);
      } catch {
      }
    };

    poll();
    const id = window.setInterval(poll, 10000);
    return () => {
      cancelled = true;
      window.clearInterval(id);
    };
  }, [player?.id, isAuthenticated, hasGang]);

  return (
    <header
      className="w-full flex items-center justify-between px-4 shrink-0"
      style={{
        height: 'var(--header-height)',
        background: 'linear-gradient(180deg, var(--bg-header) 0%, var(--bg-primary) 100%)',
        borderBottom: '1px solid var(--border-dark)',
      }}
    >
      {/* Left: Logo + clock chip */}
      <div className="flex items-center gap-3 shrink-0">
        <a href="/" className="flex items-center gap-2">
          <Image src="/images/logo.png" alt="Ombres & Lumières" width={44} height={44} priority />
          <span className="font-gothic text-gold-gradient text-lg hidden md:block">
            Ombres & Lumières
          </span>
        </a>
        {isAuthenticated && (
          <span className="chip-clock" aria-label="Heure de jeu">
            {time || '--:--'}
          </span>
        )}
      </div>

      {/* Center: Gauges (only when authenticated & in game) */}
      {isAuthenticated && gauges && (
        <div className="flex items-end gap-2 overflow-x-auto mx-4 flex-1 justify-center">
          {GAUGE_CONFIG.map((g) => {
            // Phase 8 v2 (2026-05-01) — physical_health vient de health.*
            // (single source PlayerHealth), les autres jauges restent dans
            // gauges.* (player_gauges). Branch ternaire pour résoudre la source.
            const value = g.storeKey === 'physical_health'
              ? (health?.physical_health ?? 0)
              : ((gauges as any)[g.storeKey] ?? 0);
            const max = g.storeKey === 'fortune' ? 100000 : 100;
            const IconComponent = GAUGE_ICONS[g.storeKey];

            return (
              <GaugeBar
                key={g.storeKey}
                label={
                  IconComponent ? (
                    <IconComponent size={14} color={g.color} />
                  ) : (
                    g.storeKey
                  )
                }
                value={value}
                max={max}
                color={g.color}
                tooltip={t(`gauges.${g.storeKey}`)}
              />
            );
          })}
        </div>
      )}

      {/* Right: Actions */}
      <div className="flex items-center gap-2 shrink-0 header-actions">
        {isAuthenticated && (
          <>
            {/* Messagerie */}
            <div className="relative" ref={msgRef}>
              <button
                onClick={() => setShowMessages(!showMessages)}
                className="relative p-1.5 rounded hover:bg-[var(--bg-hover)] transition-colors"
                aria-label="Messages"
              >
                <MessageSquare size={18} style={{ color: 'var(--text-secondary)' }} />
                {totalMessageBadge > 0 && (
                  <span
                    className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full text-[10px] font-bold flex items-center justify-center"
                    style={{ background: 'var(--color-red)', color: '#fff' }}
                  >
                    {totalMessageBadge > 9 ? '9+' : totalMessageBadge}
                  </span>
                )}
              </button>
              {showMessages && (
                <div
                  className="absolute right-0 top-full mt-1 w-72 rounded-lg shadow-xl z-50 p-3 max-h-72 overflow-y-auto"
                  style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
                >
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>Messages</p>
                    {proximityUnread > 0 && (
                      <span className="text-[10px]" style={{ color: 'var(--color-gold)' }}>Proximité: {proximityUnread > 9 ? '9+' : proximityUnread}</span>
                    )}
                  </div>

                  <div className="flex gap-1 mb-2">
                    <button
                      type="button"
                      onClick={() => setMessageTab('perso')}
                      className="flex-1 px-2 py-1.5 rounded text-[10px] font-semibold"
                      style={{
                        background: messageTab === 'perso' ? 'var(--bg-hover)' : 'transparent',
                        border: '1px solid var(--border-dark)',
                        color: 'var(--text-primary)',
                      }}
                    >
                      Perso{unreadMessages ? ` (${unreadMessages > 9 ? '9+' : unreadMessages})` : ''}
                    </button>
                    <button
                      type="button"
                      onClick={() => setMessageTab('equipe')}
                      disabled={!hasGang}
                      className="flex-1 px-2 py-1.5 rounded text-[10px] font-semibold disabled:opacity-50"
                      style={{
                        background: messageTab === 'equipe' ? 'var(--bg-hover)' : 'transparent',
                        border: '1px solid var(--border-dark)',
                        color: 'var(--text-primary)',
                      }}
                    >
                      Équipe{teamUnread ? ` (${teamUnread > 9 ? '9+' : teamUnread})` : ''}
                    </button>
                  </div>

                  {messageTab === 'perso' ? (
                    msgLoading ? (
                      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>...</p>
                    ) : messages.length === 0 ? (
                      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Aucun message</p>
                    ) : (
                      <div className="space-y-1.5">
                        {messages.slice(0, 15).map((msg) => (
                          <div
                            key={msg.id}
                            className="p-2 rounded transition-colors hover:bg-[var(--bg-hover)]"
                            style={{ opacity: msg.is_read ? 0.6 : 1, borderLeft: msg.is_read ? 'none' : '2px solid var(--color-gold)' }}
                          >
                            <p className="text-[10px] font-semibold" style={{ color: 'var(--text-primary)' }}>{msg.sender_name}</p>
                            <p className="text-[9px] truncate" style={{ color: 'var(--text-muted)' }}>{msg.content}</p>
                          </div>
                        ))}
                      </div>
                    )
                  ) : (
                    teamLoading ? (
                      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>...</p>
                    ) : teamMessages.length === 0 ? (
                      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Aucun message</p>
                    ) : (
                      <div className="space-y-1.5">
                        {teamMessages.slice(-15).map((m: any, idx: number) => (
                          <div key={m.id || idx} className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.04)' }}>
                            <p className="text-[10px] font-semibold" style={{ color: 'var(--text-primary)' }}>{m.sender_username || m.sender_name || 'Inconnu'}</p>
                            <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{m.content}</p>
                          </div>
                        ))}
                      </div>
                    )
                  )}
                </div>
              )}
            </div>

            {/* Notifications */}
            <div className="relative" ref={notifRef}>
              <button
                onClick={() => setShowNotifications(!showNotifications)}
                className="relative p-1.5 rounded hover:bg-[var(--bg-hover)] transition-colors"
                aria-label="Notifications"
              >
                <Bell size={18} style={{ color: 'var(--text-secondary)' }} />
                {unreadCount > 0 && (
                  <span
                    className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full text-[10px] font-bold flex items-center justify-center"
                    style={{ background: 'var(--color-red)', color: '#fff' }}
                  >
                    {unreadCount > 9 ? '9+' : unreadCount}
                  </span>
                )}
              </button>
              {showNotifications && (
                <div
                  className="absolute right-0 top-full mt-1 w-80 rounded-lg shadow-xl z-50 p-3 max-h-80 overflow-y-auto"
                  style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
                >
                  <div className="flex items-center justify-between mb-2">
                    <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
                      Notifications
                    </p>
                    {unreadCount > 0 && (
                      <button
                        onClick={async () => {
                          if (!player?.id) return;
                          try {
                            await apiFetch(`/api/player/${player.id}/notifications/read-all`, { method: 'PUT' });
                            setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
                          } catch {
                          }
                        }}
                        className="text-[10px] underline"
                        style={{ color: 'var(--color-gold)' }}
                      >
                        Tout lire
                      </button>
                    )}
                  </div>
                  {notifLoading ? (
                    <p className="text-xs" style={{ color: 'var(--text-muted)' }}>...</p>
                  ) : notifications.length === 0 ? (
                    <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
                      Aucune notification
                    </p>
                  ) : (
                    <div className="space-y-1.5">
                      {notifications.slice(0, 20).map((notif) => (
                        <div
                          key={notif.id}
                          onClick={() => !notif.is_read && markAsRead(notif.id)}
                          className="p-2 rounded cursor-pointer transition-colors hover:bg-[var(--bg-hover)]"
                          style={{
                            opacity: notif.is_read ? 0.6 : 1,
                            borderLeft: notif.is_read ? 'none' : '2px solid var(--color-gold)',
                          }}
                        >
                          <p className="text-xs font-semibold truncate" style={{ color: 'var(--text-primary)' }}>
                            {notif.title}
                          </p>
                          <p className="text-[10px] mt-0.5 line-clamp-2" style={{ color: 'var(--text-muted)' }}>
                            {notif.message}
                          </p>
                          <p className="text-[9px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
                            {new Date(notif.created_at).toLocaleDateString('fr-FR', {
                              day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit',
                            })}
                          </p>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Paramètres */}
            <button
              onClick={() => router.push('/account')}
              className="p-1.5 rounded hover:bg-[var(--bg-hover)] transition-colors"
            >
              <Settings size={18} style={{ color: 'var(--text-secondary)' }} />
            </button>
          </>
        )}
        <LanguageSelector />
        {isAuthenticated && player && (
          <div
            className="avatar-wrap-v2"
            onClick={() => router.push('/account')}
            role="button"
            tabIndex={0}
            aria-label="Compte"
          >
            <span className="avatar-name hidden xl:block max-w-[140px] truncate">
              {player.character_name || player.username}
            </span>
            <div className="avatar">
              {(player.character_name || player.username).charAt(0).toUpperCase()}
            </div>
          </div>
        )}
      </div>
    </header>
  );
}
