export const StreamScheduler: React.FC<{ sellerId: string }> = ({ sellerId }) => {
  const [streams, setStreams] = useState<Stream[]>([]);
  const [isGoingLive, setIsGoingLive] = useState(false);
  const router = useRouter();

  const handleGoLive = async () => {
    setIsGoingLive(true);
    
    try {
      // 1. Create YouTube broadcast
      const { stream } = await api.post('/streams/create', {
        title: `Live Beauty Session - ${new Date().toLocaleDateString()}`,
        description: 'Join me for exclusive beauty deals!',
        scheduledAt: new Date(), // Immediate
        products: selectedProducts,
      });

      // 2. Get RTMP credentials for OBS/Streamlabs
      const { rtmpsUrl, streamKey } = stream;

      // 3. Show RTMP setup instructions
      toast.info(`Stream Key: ${streamKey}`, {
        duration: 10000,
        action: {
          label: 'Copy Key',
          onClick: () => navigator.clipboard.writeText(streamKey),
        },
      });

      // 4. Poll for stream health
      const healthCheck = setInterval(async () => {
        const health = await api.get(`/streams/${stream.id}/health`);
        
        if (health.status === 'live') {
          clearInterval(healthCheck);
          router.push(`/live/${stream.id}`);
        }
      }, 3000);

    } catch (error) {
      toast.error('Failed to start stream');
    } finally {
      setIsGoingLive(false);
    }
  };

  return (
    <div className="p-6 bg-white rounded-xl shadow-lg">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Stream Schedule</h2>
        <button
          onClick={handleGoLive}
          disabled={isGoingLive}
          className="px-6 py-3 bg-red-500 hover:bg-red-600 text-white rounded-full font-bold flex items-center gap-2"
        >
          {isGoingLive ? <Loader className="animate-spin" /> : <Video />}
          GO LIVE NOW
        </button>
      </div>

      {/* Upcoming Streams Calendar */}
      <Calendar
        events={streams.map(s => ({
          id: s.id,
          title: s.title,
          start: s.scheduledAt,
          status: s.status,
        }))}
        onEventClick={(stream) => router.push(`/seller/streams/${stream.id}`)}
      />

      {/* Product Selection for Stream */}
      <div className="mt-6">
        <h3 className="text-lg font-semibold mb-3">Products for Next Stream</h3>
        <ProductSelector
          sellerId={sellerId}
          onSelect={setSelectedProducts}
          maxProducts={10}
        />
      </div>
    </div>
  );
};