import { useEffect, useState, useCallback } from 'react';
import { useOutletContext } from 'react-router-dom';
import { io } from 'socket.io-client';
import { api } from '../api/client';
import Header from '../components/Layout/Header';
import SignalCard from '../components/SignalCard';

function getSocketOptions() {
  const url = import.meta.env.VITE_API_URL || undefined;
  return {
    ...(url ? { url } : {}),
    path: '/socket.io/',
    transports: ['polling', 'websocket'],
  };
}

export default function ActiveSignalsPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [signals, setSignals] = useState([]);
  const [counts, setCounts] = useState({});
  const [autoUpdate, setAutoUpdate] = useState(true);
  const [countdown, setCountdown] = useState(30);

  const fetchData = useCallback(async () => {
    const [sig, sum] = await Promise.all([
      api.get('/signals/active'),
      api.get('/signals/summary/counts'),
    ]);
    setSignals(sig.data.signals);
    setCounts(sum.data);
    setCountdown(30);
  }, []);

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

  useEffect(() => {
    if (!autoUpdate) return;
    const socket = io(getSocketOptions());
    socket.on('signals:update', () => fetchData());
    const interval = setInterval(() => {
      setCountdown((c) => {
        if (c <= 1) {
          fetchData();
          return 30;
        }
        return c - 1;
      });
    }, 1000);
    return () => {
      socket.disconnect();
      clearInterval(interval);
    };
  }, [autoUpdate, fetchData]);

  return (
    <div>
      <Header title="سیگنال‌های فعال" user={user} lastUpdate={counts.lastUpdate} onMenuClick={() => setMobileOpen?.(true)} />

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
        <div className="card text-center">
          <p className="text-gray-500 text-sm">سیگنال فعال</p>
          <p className="text-3xl font-bold text-accent">{counts.active?.toLocaleString('fa-IR') || 0}</p>
        </div>
        <div className="card text-center">
          <p className="text-gray-500 text-sm">بسته شده جدید</p>
          <p className="text-3xl font-bold">{counts.recentlyClosed?.toLocaleString('fa-IR') || 0}</p>
        </div>
        <div className="card flex items-center justify-between">
          <div>
            <p className="text-gray-500 text-sm">بروزرسانی خودکار</p>
            <p className="text-xs text-gray-600 mt-1">بروزرسانی بعدی: {countdown.toLocaleString('fa-IR')} ثانیه</p>
          </div>
          <button
            onClick={() => setAutoUpdate(!autoUpdate)}
            className={`w-14 h-8 rounded-full transition-colors relative ${autoUpdate ? 'bg-accent' : 'bg-navy-700'}`}
          >
            <span className={`absolute top-1 w-6 h-6 rounded-full bg-white transition-all ${autoUpdate ? 'right-1' : 'left-1'}`} />
          </button>
        </div>
      </div>

      <div className="space-y-4">
        {signals.length === 0 ? (
          <div className="card text-center text-gray-500 py-12">سیگنال فعالی وجود ندارد</div>
        ) : (
          signals.map((s) => <SignalCard key={s.id} signal={s} />)
        )}
      </div>
    </div>
  );
}
