'use client';

import { useState, useEffect, useCallback } from 'react';
import { Header } from '@/components/layout';
import { AppLayout } from '@/components/layout';
import { EnhancedQueueList } from '@/components/features/queue';
import { apiClient, type QueueStatus, type JobInfo } from '@/lib/api';
import { Loader2 } from 'lucide-react';

export default function QueuePage() {
  const [queueStatus, setQueueStatus] = useState<QueueStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);

  const loadQueueStatus = useCallback(async () => {
    try {
      const status = await apiClient.getQueueStatus();
      setQueueStatus(status);
    } catch (error) {
      console.error('Failed to load queue status:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadQueueStatus();
    const interval = setInterval(loadQueueStatus, 2000);
    return () => clearInterval(interval);
  }, [loadQueueStatus]);

  const cancelJob = useCallback(async (jobId: string) => {
    setActionLoading(true);
    try {
      await apiClient.cancelJob(jobId);
      await loadQueueStatus();
    } catch (error) {
      console.error('Failed to cancel job:', error);
    } finally {
      setActionLoading(false);
    }
  }, [loadQueueStatus]);

  const clearQueue = useCallback(async () => {
    setActionLoading(true);
    try {
      await apiClient.clearQueue();
      await loadQueueStatus();
    } catch (error) {
      console.error('Failed to clear queue:', error);
    } finally {
      setActionLoading(false);
    }
  }, [loadQueueStatus]);

  const copyParameters = useCallback((job: JobInfo) => {
    // This would typically copy to clipboard and show a toast
    console.log('Parameters copied for job:', job.id);
  }, []);

  if (loading) {
    return (
      <AppLayout>
        <Header title="Queue" description="Monitor and manage generation jobs" />
        <div className="container mx-auto p-6">
          <div className="flex items-center justify-center h-64">
            <Loader2 className="h-8 w-8 animate-spin" />
          </div>
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <Header title="Queue" description="Monitor and manage generation jobs" />
      <div className="container mx-auto p-6">
        <EnhancedQueueList
          queueStatus={queueStatus}
          loading={loading}
          onRefresh={loadQueueStatus}
          onCancelJob={cancelJob}
          onClearQueue={clearQueue}
          actionLoading={actionLoading}
          onCopyParameters={copyParameters}
        />
      </div>
    </AppLayout>
  );
}
