import { useState, useEffect } from 'react';
import { Table, Tag, Progress, Button, Space, Popconfirm, message, Card } from 'antd';
import { StopOutlined, DeleteOutlined, ReloadOutlined, ClearOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import dayjs from 'dayjs';
import { mediaApi } from '@/lib/media-api';
import type { Job, JobsListResponse } from '@/types/media';
import type { AppOutletContext } from '@/types/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

export default function MediaJobsPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [jobs, setJobs] = useState<Job[]>([]);
  const [selectedJob, setSelectedJob] = useState<Job | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setPageHeader({
      title: 'Processing Jobs',
      subtitle: 'Monitor media processing queue',
    });
  }, [setPageHeader]);

  useEffect(() => {
    fetchJobs();
    const interval = setInterval(fetchJobs, 5000); // Poll every 5 seconds
    return () => clearInterval(interval);
  }, []);

  const fetchJobs = async () => {
    try {
      const { data } = await mediaApi.get<JobsListResponse>('/jobs');
      setJobs(data.jobs);
    } catch (error: unknown) {
      console.error('Failed to load jobs:', error);
      // Don't show error message on polling failures to avoid spam
    }
  };

  const handleCancel = async (jobId: number) => {
    try {
      await mediaApi.post(`/jobs/${jobId}/cancel`);
      message.success('Job cancelled');
      fetchJobs();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to cancel job'));
    }
  };

  const handleDelete = async (jobId: number) => {
    try {
      await mediaApi.delete(`/jobs/${jobId}`);
      message.success('Job deleted');
      if (selectedJob?.id === jobId) {
        setSelectedJob(null);
      }
      fetchJobs();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to delete job'));
    }
  };

  const handleCleanCompleted = async () => {
    setLoading(true);
    try {
      await mediaApi.delete('/jobs/completed');
      message.success('Completed jobs cleaned up');
      fetchJobs();
    } catch (error: unknown) {
      message.error(getErrorMessage(error, 'Failed to clean up jobs'));
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      render: (type: string) => (
        <Tag>{type.replace(/_/g, ' ').toUpperCase()}</Tag>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      render: (status: Job['status']) => {
        const colors: Record<Job['status'], string> = {
          pending: 'yellow',
          queued: 'orange',
          running: 'blue',
          completed: 'green',
          failed: 'red',
          cancelled: 'default',
        };
        return <Tag color={colors[status]}>{status.toUpperCase()}</Tag>;
      },
    },
    {
      title: 'Progress',
      dataIndex: 'progress',
      width: 150,
      render: (progress: number) => <Progress percent={progress} size="small" />,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      render: (date: string) => dayjs(date).format('MMM D, HH:mm'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_: any, record: Job) => (
        <Space>
          {['pending', 'queued', 'running'].includes(record.status) && (
            <Button
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                handleCancel(record.id);
              }}
              icon={<StopOutlined />}
            >
              Cancel
            </Button>
          )}
          {record.status !== 'running' && (
            <Popconfirm
              title="Delete job?"
              description="This will permanently remove the job from the queue."
              onConfirm={(e) => {
                e?.stopPropagation();
                handleDelete(record.id);
              }}
              onCancel={(e) => e?.stopPropagation()}
            >
              <Button
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={(e) => e.stopPropagation()}
              />
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<ReloadOutlined />} onClick={fetchJobs}>
          Refresh
        </Button>
        <Button
          icon={<ClearOutlined />}
          onClick={handleCleanCompleted}
          loading={loading}
        >
          Clean Completed
        </Button>
      </Space>

      <Table
        columns={columns}
        dataSource={jobs}
        scroll={{ x: 'max-content' }}
        rowKey="id"
        pagination={false}
        onRow={(record) => ({
          onClick: () => setSelectedJob(record),
          style: { cursor: 'pointer' },
        })}
        rowClassName={(record) =>
          selectedJob?.id === record.id ? 'ant-table-row-selected' : ''
        }
      />

      {selectedJob && (
        <Card
          title={`Job #${selectedJob.id} - ${selectedJob.type.replace(/_/g, ' ').toUpperCase()}`}
          style={{ marginTop: 16 }}
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            <div>
              <strong>Status:</strong> {selectedJob.status}
            </div>
            <div>
              <strong>Progress:</strong> {selectedJob.progress}%
            </div>
            <div>
              <strong>Created:</strong> {dayjs(selectedJob.createdAt).format('MMMM D, YYYY h:mm A')}
            </div>
            {selectedJob.startedAt && (
              <div>
                <strong>Started:</strong> {dayjs(selectedJob.startedAt).format('MMMM D, YYYY h:mm A')}
              </div>
            )}
            {selectedJob.completedAt && (
              <div>
                <strong>Completed:</strong> {dayjs(selectedJob.completedAt).format('MMMM D, YYYY h:mm A')}
              </div>
            )}
            {selectedJob.queuePosition !== null && selectedJob.queuePosition !== undefined && (
              <div>
                <strong>Queue Position:</strong> {selectedJob.queuePosition}
              </div>
            )}
            {selectedJob.waitingReason && (
              <div>
                <strong>Waiting Reason:</strong> {selectedJob.waitingReason}
              </div>
            )}
            {selectedJob.log && (
              <div>
                <strong>Log:</strong>
                <pre
                  style={{
                    background: '#000',
                    color: '#0f0',
                    padding: 8,
                    maxHeight: 300,
                    overflow: 'auto',
                    borderRadius: 4,
                    marginTop: 8,
                  }}
                >
                  {selectedJob.log}
                </pre>
              </div>
            )}
          </Space>
        </Card>
      )}
    </div>
  );
}
