import React, { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Card,
  Select,
  Space,
  Table,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { customRequest } from 'helpers/http';

const { Title } = Typography;
const PAGE_SIZE = 20;

const STATUS_TAG: Record<string, { color: string; label: string }> = {
  PENDING: { color: 'gold', label: 'Pending' },
  RUNNING: { color: 'blue', label: 'Running' },
  COMPLETED: { color: 'green', label: 'Completed' },
  FAILED: { color: 'red', label: 'Failed' },
  CANCELLED: { color: 'default', label: 'Cancelled' },
};

interface WorkflowInstanceItem {
  id: string;
  status: string;
  startedAt: string | null;
  finishedAt: string | null;
  creator: string;
  createdAt: string;
}

function formatDuration(start: string | null, end: string | null): string {
  if (!start || !end) return '—';
  const ms = new Date(end).getTime() - new Date(start).getTime();
  if (ms < 1000) return `${ms}ms`;
  const s = Math.floor(ms / 1000);
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  const rem = s % 60;
  return rem > 0 ? `${m}m ${rem}s` : `${m}m`;
}

export default function WorkflowInstancesPage() {
  const { workflowId } = useParams<{ workflowId: string }>();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();

  const filterStatus = searchParams.get('status') || undefined;
  const page = Number(searchParams.get('page')) || 1;

  const [items, setItems] = useState<WorkflowInstanceItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [workflowName, setWorkflowName] = useState('');

  const updateParams = useCallback(
    (updates: Record<string, string | undefined>) => {
      setSearchParams(
        (prev) => {
          const next = new URLSearchParams(prev);
          for (const [k, v] of Object.entries(updates)) {
            if (v) next.set(k, v);
            else next.delete(k);
          }
          return next;
        },
        { replace: true },
      );
    },
    [setSearchParams],
  );

  useEffect(() => {
    if (!workflowId) return;
    customRequest<{ name: string }>(`workflow/${workflowId}`, 'GET')
      .then((wf) => setWorkflowName(wf.name))
      .catch(() => {});
  }, [workflowId]);

  const fetchData = useCallback(async () => {
    if (!workflowId) return;
    setLoading(true);
    try {
      const params: Record<string, any> = {
        skip: (page - 1) * PAGE_SIZE,
        limit: PAGE_SIZE,
      };
      if (filterStatus) params.status = filterStatus;

      const res = await customRequest<{
        items: WorkflowInstanceItem[];
        total: number;
      }>(`workflow/${workflowId}/instances`, 'GET', params);
      setItems(res.items);
      setTotal(res.total);
    } catch {
      // handled silently
    } finally {
      setLoading(false);
    }
  }, [workflowId, page, filterStatus]);

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

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 110,
      render: (status: string) => {
        const cfg = STATUS_TAG[status] || { color: 'default', label: status };
        return <Tag color={cfg.color}>{cfg.label}</Tag>;
      },
    },
    {
      title: 'Started',
      dataIndex: 'startedAt',
      key: 'startedAt',
      width: 160,
      render: (v: string | null) =>
        v ? (
          <Tooltip title={new Date(v).toLocaleString()}>
            <span>{new Date(v).toLocaleString()}</span>
          </Tooltip>
        ) : (
          <span style={{ color: '#d9d9d9' }}>—</span>
        ),
    },
    {
      title: 'Finished',
      dataIndex: 'finishedAt',
      key: 'finishedAt',
      width: 160,
      render: (v: string | null) =>
        v ? (
          <Tooltip title={new Date(v).toLocaleString()}>
            <span>{new Date(v).toLocaleString()}</span>
          </Tooltip>
        ) : (
          <span style={{ color: '#d9d9d9' }}>—</span>
        ),
    },
    {
      title: 'Duration',
      key: 'duration',
      width: 100,
      render: (_: any, record: WorkflowInstanceItem) =>
        formatDuration(record.startedAt, record.finishedAt),
    },
    {
      title: 'Creator',
      dataIndex: 'creator',
      key: 'creator',
      width: 150,
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_: any, record: WorkflowInstanceItem) => (
        <Button
          type="link"
          size="small"
          onClick={() => navigate(`/admin/workflow/instance/show/${record.id}`)}
        >
          Detail
        </Button>
      ),
    },
  ];

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 64px)' }}>
      <Card style={{ marginBottom: 16 }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Space>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/admin/workflow')}
            ></Button>
            <Title level={4} style={{ margin: 0 }}>
              {workflowName || 'Workflow'} — Execution History
            </Title>
          </Space>
          <Select
            placeholder="All Statuses"
            allowClear
            value={filterStatus}
            onChange={(v) => updateParams({ status: v, page: undefined })}
            style={{ width: 140 }}
            options={[
              { value: 'PENDING', label: 'Pending' },
              { value: 'RUNNING', label: 'Running' },
              { value: 'COMPLETED', label: 'Completed' },
              { value: 'FAILED', label: 'Failed' },
              { value: 'CANCELLED', label: 'Cancelled' },
            ]}
          />
        </div>
      </Card>

      <Card>
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={items}
          pagination={{
            current: page,
            pageSize: PAGE_SIZE,
            total,
            onChange: (p) =>
              updateParams({ page: p > 1 ? String(p) : undefined }),
            showTotal: (t) => `Total ${t}`,
          }}
          size="small"
        />
      </Card>
    </div>
  );
}
