import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Button,
  Card,
  Input,
  Modal,
  Popconfirm,
  Select,
  Space,
  Switch,
  Table,
  Tag,
  Tooltip,
  Typography,
  message,
} from 'antd';
import {
  DatabaseOutlined,
  DeleteOutlined,
  EditOutlined,
  ExportOutlined,
  EyeOutlined,
  HistoryOutlined,
  ImportOutlined,
  PlusOutlined,
  ReloadOutlined,
  SendOutlined,
} from '@ant-design/icons';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { customRequest } from 'helpers/http';
import { StatusCards } from './components/StatusCards';
import { ExportModal } from './components/ExportModal';
import { ImportModal } from './components/ImportModal';
import type { Workflow, WorkflowOverview } from './types';

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

function RunDot({
  count,
  color,
  label,
  onClick,
}: {
  count: number;
  color: string;
  label: string;
  onClick?: () => void;
}) {
  const size = 28;
  const hasCount = count > 0;
  return (
    <Tooltip title={`${label}: ${count}`}>
      <span
        onClick={hasCount ? onClick : undefined}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          width: size,
          height: size,
          borderRadius: '50%',
          border: `2.5px solid ${hasCount ? color : '#d9d9d9'}`,
          fontSize: 11,
          fontWeight: 600,
          color: hasCount ? color : '#d9d9d9',
          cursor: hasCount && onClick ? 'pointer' : 'default',
          lineHeight: 1,
        }}
      >
        {hasCount ? count : ''}
      </span>
    </Tooltip>
  );
}

const STATUS_COLOR: Record<string, string> = {
  DRAFT: 'default',
  PUBLISHED: 'success',
};

export default function WorkflowListPage() {
  console.log('[WorkflowList] MOUNTED, pathname:', window.location.pathname);
  const navigate = useNavigate();
  const [workflows, setWorkflows] = useState<Workflow[]>([]);
  const [overview, setOverview] = useState<WorkflowOverview | null>(null);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const [searchParams, setSearchParams] = useSearchParams();
  const filterStatus = searchParams.get('status') || undefined;
  const filterInstanceStatus = searchParams.get('instanceStatus') || undefined;
  const filterName = searchParams.get('name') || undefined;
  const page = Number(searchParams.get('page')) || 1;

  const [publishModalOpen, setPublishModalOpen] = useState(false);
  const [publishId, setPublishId] = useState<string | null>(null);
  const [publishSummary, setPublishSummary] = useState('');
  const [publishLoading, setPublishLoading] = useState(false);

  const [exportModalOpen, setExportModalOpen] = useState(false);
  const [exportWorkflowId, setExportWorkflowId] = useState<string | null>(null);
  const [importModalOpen, setImportModalOpen] = useState(false);

  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  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],
  );

  const setFilterStatus = useCallback(
    (v: string | undefined) => updateParams({ status: v, page: undefined }),
    [updateParams],
  );
  const setFilterInstanceStatus = useCallback(
    (v: string | undefined) =>
      updateParams({ instanceStatus: v, page: undefined }),
    [updateParams],
  );
  const setFilterName = useCallback(
    (v: string | undefined) => updateParams({ name: v, page: undefined }),
    [updateParams],
  );
  const setPage = useCallback(
    (p: number) => updateParams({ page: p > 1 ? String(p) : undefined }),
    [updateParams],
  );

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

      const [listRes, overviewRes] = await Promise.all([
        customRequest<{ items: Workflow[]; total: number }>(
          'workflow',
          'GET',
          params,
        ),
        customRequest<WorkflowOverview>('workflow/overview', 'GET'),
      ]);
      setWorkflows(listRes.items);
      setTotal(listRes.total);
      setOverview(overviewRes);
    } catch (e: any) {
      message.error(e?.message ?? 'Failed to fetch workflows');
    } finally {
      setLoading(false);
    }
  }, [page, filterStatus, filterInstanceStatus, filterName]);

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

  async function handleDelete(id: string) {
    try {
      await customRequest(`workflow/${id}`, 'DELETE');
      message.success('Workflow deleted');
      fetchData();
    } catch (e: any) {
      message.error(e?.message ?? 'Delete failed');
    }
  }

  async function handlePublish() {
    if (!publishId) return;
    setPublishLoading(true);
    try {
      await customRequest(`workflow/${publishId}/publish`, 'POST', {
        changeSummary: publishSummary,
      });
      message.success('Workflow published!');
      setPublishModalOpen(false);
      setPublishId(null);
      setPublishSummary('');
      fetchData();
    } catch (e: any) {
      message.error(e?.message ?? 'Publish failed');
    } finally {
      setPublishLoading(false);
    }
  }

  async function handleToggleEnabled(id: string, currentValue: boolean) {
    try {
      await customRequest(`workflow/${id}/toggle`, 'PATCH', {
        enabled: !currentValue,
      });
      message.success(`Workflow ${currentValue ? '禁用' : '启用'}成功`);
      fetchData();
    } catch (e: any) {
      message.error(e?.message ?? 'Toggle failed');
    }
  }

  const columns = [
    {
      title: '',
      dataIndex: 'isEnabled',
      key: 'isEnabled',
      width: 50,
      render: (isEnabled: boolean, record: Workflow) => (
        <Popconfirm
          title={`确定要${isEnabled ? '禁用' : '启用'}此工作流?`}
          okText="确定"
          cancelText="取消"
          onConfirm={() => handleToggleEnabled(record.id, isEnabled)}
        >
          <Switch checked={isEnabled} size="small" />
        </Popconfirm>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: Workflow) => (
        <a onClick={() => navigate(`/admin/workflow/show/${record.id}`)}>
          {name}
        </a>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={STATUS_COLOR[status]}>{status}</Tag>
      ),
    },
    {
      title: 'Version',
      key: 'version',
      width: 200,
      render: (_: any, record: Workflow) => {
        const ver = record.versions?.[0];
        if (!ver) return '—';
        const summary = ver.changeSummary?.slice(0, 20) || '';
        return summary ? `v${ver.version} - ${summary}` : `v${ver.version}`;
      },
    },
    {
      title: 'Runs',
      key: 'runs',
      width: 160,
      render: (_: any, record: Workflow) => {
        const runs = record.runs || {
          pending: 0,
          running: 0,
          completed: 0,
          failed: 0,
        };
        const go = (status: string) =>
          navigate(
            `/admin/workflow/instances/show/${record.id}?status=${status}`,
          );
        return (
          <Space size={4}>
            <RunDot
              count={runs.pending}
              color="#faad14"
              label="Pending"
              onClick={() => go('PENDING')}
            />
            <RunDot
              count={runs.completed}
              color="#006d32"
              label="Completed"
              onClick={() => go('COMPLETED')}
            />
            <RunDot
              count={runs.running}
              color="#52c41a"
              label="Running"
              onClick={() => go('RUNNING')}
            />
            <RunDot
              count={runs.failed}
              color="#ff4d4f"
              label="Failed"
              onClick={() => go('FAILED')}
            />
          </Space>
        );
      },
    },
    {
      title: 'Last Run',
      key: 'lastRun',
      width: 150,
      render: (_: any, record: Workflow) => {
        if (!record.lastRun) return <span style={{ color: '#d9d9d9' }}>—</span>;
        return (
          <Tooltip title={new Date(record.lastRun).toLocaleString()}>
            <span>{new Date(record.lastRun).toLocaleDateString()}</span>
          </Tooltip>
        );
      },
    },
    {
      title: 'Updated',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 150,
      render: (v: string) => (
        <Tooltip title={new Date(v).toLocaleString()}>
          <span>{new Date(v).toLocaleDateString()}</span>
        </Tooltip>
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 180,
      render: (_: any, record: Workflow) => (
        <Space>
          <Tooltip title="View">
            <Button
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/admin/workflow/show/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="Edit">
            <Button
              size="small"
              icon={<EditOutlined />}
              onClick={() => navigate(`/admin/workflow/edit/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="Run History">
            <Button
              size="small"
              icon={<HistoryOutlined />}
              onClick={() =>
                navigate(`/admin/workflow/instances/show/${record.id}`)
              }
            />
          </Tooltip>
          <Tooltip title="Export">
            <Button
              size="small"
              icon={<ExportOutlined />}
              onClick={() => {
                setExportWorkflowId(record.id);
                setExportModalOpen(true);
              }}
            />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Tooltip title="Publish">
              <Button
                size="small"
                type="primary"
                icon={<SendOutlined />}
                onClick={() => {
                  setPublishId(record.id);
                  setPublishSummary('');
                  setPublishModalOpen(true);
                }}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="Delete this workflow?"
            description="All versions and instances will be deleted."
            okText="Delete"
            cancelText="Cancel"
            okButtonProps={{ danger: true }}
            onConfirm={() => handleDelete(record.id)}
          >
            <Tooltip title="Delete">
              <Button size="small" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 64px)' }}>
      <Card style={{ marginBottom: 16 }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Title level={4} style={{ margin: 0 }}>
            Workflows
          </Title>
          <Space>
            <Tooltip title="查看 WorkflowEventOutbox 表原始数据">
              <Button
                icon={<DatabaseOutlined />}
                onClick={() =>
                  navigate('/admin/data-mngt/workflow-event-outbox')
                }
              >
                PG表事件队列
              </Button>
            </Tooltip>
            <Button
              icon={<ImportOutlined />}
              onClick={() => setImportModalOpen(true)}
            >
              Import
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => navigate('/admin/workflow/create')}
            >
              New Workflow
            </Button>
            <Button icon={<ReloadOutlined />} onClick={fetchData} />
          </Space>
        </div>
      </Card>

      <StatusCards
        overview={overview}
        activeFilter={filterInstanceStatus}
        onFilter={setFilterInstanceStatus}
      />

      <Card style={{ marginBottom: 16 }}>
        <Space wrap>
          <Select
            placeholder="Status"
            allowClear
            value={filterStatus}
            onChange={(v) => setFilterStatus(v)}
            style={{ width: 120 }}
            options={[
              { value: 'draft', label: 'Draft' },
              { value: 'published', label: 'Published' },
            ]}
          />
          <Input
            placeholder="Search by name"
            allowClear
            defaultValue={filterName}
            onChange={(e) => {
              const v = e.target.value;
              if (debounceRef.current) clearTimeout(debounceRef.current);
              debounceRef.current = setTimeout(
                () => setFilterName(v || undefined),
                300,
              );
            }}
            style={{ width: 220 }}
          />
        </Space>
      </Card>

      <Card>
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={workflows}
          scroll={{ x: 'max-content' }}
          pagination={{
            current: page,
            pageSize: PAGE_SIZE,
            total,
            onChange: (p) => setPage(p),
            showTotal: (t) => `Total ${t}`,
          }}
          size="small"
        />
      </Card>

      <Modal
        title="Publish Workflow"
        open={publishModalOpen}
        onOk={handlePublish}
        onCancel={() => {
          setPublishModalOpen(false);
          setPublishId(null);
          setPublishSummary('');
        }}
        okText="Publish"
        cancelText="Cancel"
        confirmLoading={publishLoading}
      >
        <p>Please enter a version description:</p>
        <Input.TextArea
          rows={3}
          placeholder="Describe what changed in this version..."
          value={publishSummary}
          onChange={(e) => setPublishSummary(e.target.value)}
        />
      </Modal>

      <ExportModal
        open={exportModalOpen}
        workflowId={exportWorkflowId}
        onClose={() => {
          setExportModalOpen(false);
          setExportWorkflowId(null);
        }}
      />

      <ImportModal
        open={importModalOpen}
        onClose={() => setImportModalOpen(false)}
        onSuccess={fetchData}
      />
    </div>
  );
}
