import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw, Search, SlidersHorizontal } from 'lucide-react';
import type { AdminGatewayTask, GatewayTask } from '@easyai-ai-gateway/contracts';
import { getAdminTask, listAdminTaskParamPreprocessing } from '../../api';
import {
  Button,
  Card,
  CardContent,
  ConfirmDialog,
  DateTimeRangePicker,
  FormDialog,
  Input,
  Label,
  Select,
  Table,
  TableFooter,
  TableHead,
  TablePageActions,
  TableRow,
  TableToolbar,
  TableViewportLayout,
} from '../../components/ui';
import type { ConsoleData } from '../../app-state';
import type { AdminTaskQuery, LoadState } from '../../types';
import { TaskRecord } from '../WorkspacePage';

const taskPageSizeOptions = [10, 20, 50, 100];
const taskStatuses = ['queued', 'submitting', 'running', 'succeeded', 'failed', 'cancelled'];
const billingStatuses = ['not_started', 'pending', 'processing', 'settled', 'released', 'retryable_failed', 'manual_review', 'not_required'];
type AdminTaskAdvancedFilters = Pick<
  AdminTaskQuery,
  'tenantId' | 'userId' | 'userGroupId' | 'status' | 'platformId' | 'model' | 'modelType' | 'runMode' | 'billingStatus' | 'apiKey'
>;

export function AdminTasksPanel(props: {
  data: ConsoleData;
  query: AdminTaskQuery;
  state: LoadState;
  token: string;
  total: number;
  updatedAt: number | null;
  onQueryChange: (query: AdminTaskQuery) => void;
  onRefresh: () => Promise<void>;
}) {
  const [localMessage, setLocalMessage] = useState('');
  const [pageJump, setPageJump] = useState(String(props.query.page));
  const [detail, setDetail] = useState<AdminGatewayTask | null>(null);
  const [detailSensitive, setDetailSensitive] = useState<'masked' | 'full'>('masked');
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailError, setDetailError] = useState('');
  const [revealConfirmOpen, setRevealConfirmOpen] = useState(false);
  const [advancedFilterOpen, setAdvancedFilterOpen] = useState(false);
  const [advancedFilterDraft, setAdvancedFilterDraft] = useState<AdminTaskAdvancedFilters>(() => adminTaskAdvancedFilters(props.query));
  const query = props.query;
  const tasks = props.data.adminTasks;
  const { totalPages, currentPage, pageStart, pageEnd } = adminTaskPagination(props.total, query.page, query.pageSize);
  const hasActiveFilters = adminTaskHasActiveFilters(query);
  const advancedFilterCount = adminTaskAdvancedFilterCount(query);
  const users = useMemo(
    () => props.data.users.slice().sort((a, b) => adminUserLabel(a).localeCompare(adminUserLabel(b))),
    [props.data.users],
  );
  const tenants = useMemo(
    () => props.data.tenants.slice().sort((a, b) => (a.name || a.tenantKey).localeCompare(b.name || b.tenantKey)),
    [props.data.tenants],
  );
  const platforms = useMemo(
    () => props.data.platforms.slice().sort((a, b) => (a.internalName || a.name).localeCompare(b.internalName || b.name)),
    [props.data.platforms],
  );
  const models = useMemo(() => {
    const values = props.data.models
      .flatMap((model) => [model.modelAlias, model.modelName, model.providerModelName])
      .filter((value): value is string => Boolean(value));
    return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
  }, [props.data.models]);
  const modelTypes = useMemo(() => {
    const values = [
      ...props.data.models.flatMap((model) => model.modelType),
      ...tasks.map((task) => task.modelType || ''),
    ].filter((value): value is string => Boolean(value));
    return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
  }, [props.data.models, tasks]);

  useEffect(() => {
    if (query.page > totalPages) {
      props.onQueryChange({ ...query, page: totalPages });
    }
  }, [props.onQueryChange, query, totalPages]);

  useEffect(() => {
    setPageJump(String(currentPage));
  }, [currentPage]);

  function updateQuery(patch: Partial<AdminTaskQuery>) {
    props.onQueryChange({ ...query, ...patch, page: patch.page ?? 1 });
  }

  function resetFilters() {
    props.onQueryChange({
      query: '',
      tenantId: '',
      userId: '',
      userGroupId: '',
      status: '',
      platformId: '',
      model: '',
      modelType: '',
      runMode: '',
      billingStatus: '',
      apiKey: '',
      createdFrom: '',
      createdTo: '',
      page: 1,
      pageSize: query.pageSize,
    });
  }

  function openAdvancedFilters() {
    setAdvancedFilterDraft(adminTaskAdvancedFilters(query));
    setAdvancedFilterOpen(true);
  }

  function updateAdvancedFilter(patch: Partial<AdminTaskAdvancedFilters>) {
    setAdvancedFilterDraft((current) => ({ ...current, ...patch }));
  }

  function clearAdvancedFilters() {
    setAdvancedFilterDraft(emptyAdminTaskAdvancedFilters());
  }

  function applyAdvancedFilters() {
    props.onQueryChange({ ...query, ...advancedFilterDraft, page: 1 });
    setAdvancedFilterOpen(false);
  }

  async function copyTaskRequestId(task: GatewayTask) {
    if (!task.requestId) return;
    await navigator.clipboard.writeText(task.requestId);
    setLocalMessage(`已复制 RequestID：${task.requestId}`);
  }

  async function openDetail(task: GatewayTask) {
    setDetailError('');
    setDetailLoading(true);
    setDetailSensitive('masked');
    setDetail('adminContext' in task ? task as AdminGatewayTask : null);
    try {
      setDetail(await getAdminTask(props.token, task.id, 'masked'));
    } catch (err) {
      setDetailError(err instanceof Error ? err.message : '加载任务详情失败');
    } finally {
      setDetailLoading(false);
    }
  }

  async function revealSensitiveDetail() {
    if (!detail) return;
    setRevealConfirmOpen(false);
    setDetailLoading(true);
    setDetailError('');
    try {
      setDetail(await getAdminTask(props.token, detail.id, 'full'));
      setDetailSensitive('full');
    } catch (err) {
      setDetailError(err instanceof Error ? err.message : '加载完整任务详情失败');
    } finally {
      setDetailLoading(false);
    }
  }

  function submitPageJump() {
    const parsed = Number(pageJump);
    if (!Number.isFinite(parsed) || parsed <= 0) {
      setPageJump(String(currentPage));
      return;
    }
    props.onQueryChange({ ...query, page: Math.min(totalPages, Math.max(1, Math.floor(parsed))) });
  }

  return (
    <section className="pageStack">
      <Card className="shTableViewportCard adminTaskRecordViewport">
        <CardContent className="shTableViewportPanel">
          {localMessage && <p className="formMessage">{localMessage}</p>}
          <TableViewportLayout>
            <TableToolbar className="adminTaskFilters">
              <Label className="adminTaskSearchLabel">
                搜索
                <span className="taskRecordSearchBox">
                  <Search size={15} />
                  <Input
                    value={query.query}
                    placeholder="任务、用户、租户、模型、平台、RequestID"
                    onChange={(event) => updateQuery({ query: event.target.value })}
                  />
                </span>
              </Label>
              <Label className="adminTaskRangeLabel">
                创建时间
                <DateTimeRangePicker
                  from={query.createdFrom}
                  fromPlaceholder="开始日期"
                  to={query.createdTo}
                  toPlaceholder="结束日期"
                  onChange={(value) => updateQuery({ createdFrom: value.from, createdTo: value.to })}
                />
              </Label>
              <div className="adminTaskToolbarActions">
                <Button type="button" variant="outline" size="sm" onClick={openAdvancedFilters}>
                  <SlidersHorizontal size={14} />
                  高级筛选{advancedFilterCount ? `（${advancedFilterCount}）` : ''}
                </Button>
                <Button type="button" variant="outline" size="sm" disabled={!hasActiveFilters} onClick={resetFilters}>
                  <RotateCcw size={14} />
                  重置
                </Button>
                <Button type="button" variant="outline" size="sm" disabled={props.state === 'loading'} onClick={() => void props.onRefresh()}>
                  <RefreshCw size={14} />
                  刷新
                </Button>
              </div>
            </TableToolbar>

            <div className="adminTaskResultSummary">
              <span>匹配 {props.total} 条任务</span>
              <small>最近刷新：{formatAdminTaskUpdatedAt(props.updatedAt)}</small>
            </div>

            {tasks.length ? (
              <Table className="shTableViewport adminTaskRecordTable" density="compact">
                <TableRow className="shTableHeader">
                  <TableHead>任务</TableHead>
                  <TableHead>用户 / 租户</TableHead>
                  <TableHead>RequestID</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>运行模式</TableHead>
                  <TableHead>模型</TableHead>
                  <TableHead>最终平台</TableHead>
                  <TableHead>尝试链路</TableHead>
                  <TableHead>参数转换</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>API Key</TableHead>
                  <TableHead>Token</TableHead>
                  <TableHead>扣费</TableHead>
                  <TableHead>计费状态</TableHead>
                  <TableHead>耗时</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>原始 JSON</TableHead>
                </TableRow>
                {tasks.map((task) => (
                  <TaskRecord
                    admin
                    key={task.id}
                    task={task}
                    token={props.token}
                    onCopyRequestId={copyTaskRequestId}
                    onLoadParamPreprocessing={listAdminTaskParamPreprocessing}
                    onOpenJson={openDetail}
                  />
                ))}
              </Table>
            ) : (
              <div className="emptyState">
                <strong>{hasActiveFilters ? '没有匹配的任务' : '暂无任务'}</strong>
                <span>{hasActiveFilters ? '调整筛选条件后再试。' : '任务创建后会在这里显示。'}</span>
              </div>
            )}

            <TableFooter>
              <div className="shTableFooterGroup">
                <Label>
                  每页
                  <Select
                    size="sm"
                    value={String(query.pageSize)}
                    onChange={(event) => props.onQueryChange({ ...query, page: 1, pageSize: Number(event.target.value) })}
                  >
                    {taskPageSizeOptions.map((option) => <option key={option} value={option}>{option} 条</option>)}
                  </Select>
                </Label>
                <span>共 {props.total} 条 · {pageStart}-{pageEnd}</span>
              </div>
              <form
                className="shTablePageJump"
                onSubmit={(event) => {
                  event.preventDefault();
                  submitPageJump();
                }}
              >
                <span>第 {currentPage} / {totalPages} 页</span>
                <span>跳至</span>
                <Input
                  aria-label="跳转页码"
                  inputMode="numeric"
                  min={1}
                  max={totalPages}
                  size="xs"
                  type="number"
                  value={pageJump}
                  onChange={(event) => setPageJump(event.target.value)}
                />
                <span>页</span>
                <Button type="submit" variant="outline" size="xs" disabled={totalPages <= 1}>跳转</Button>
              </form>
              <TablePageActions>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={currentPage <= 1}
                  onClick={() => props.onQueryChange({ ...query, page: Math.max(1, currentPage - 1) })}
                >
                  <ChevronLeft size={14} />
                  上一页
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={currentPage >= totalPages}
                  onClick={() => props.onQueryChange({ ...query, page: Math.min(totalPages, currentPage + 1) })}
                >
                  下一页
                  <ChevronRight size={14} />
                </Button>
              </TablePageActions>
            </TableFooter>
          </TableViewportLayout>
        </CardContent>
      </Card>

      <FormDialog
        ariaLabel="管理员任务高级筛选"
        bodyClassName="adminTaskAdvancedDialogBody"
        className="adminTaskAdvancedDialog"
        closeLabel="关闭"
        footer={(
          <>
            <Button type="button" variant="outline" disabled={!adminTaskAdvancedFilterCount(advancedFilterDraft)} onClick={clearAdvancedFilters}>
              <RotateCcw size={15} />
              清空高级条件
            </Button>
            <Button type="submit">
              <SlidersHorizontal size={15} />
              应用筛选
            </Button>
          </>
        )}
        open={advancedFilterOpen}
        title="高级筛选"
        onClose={() => setAdvancedFilterOpen(false)}
        onSubmit={(event) => {
          event.preventDefault();
          applyAdvancedFilters();
        }}
      >
        <FilterSelect
          label="租户"
          value={advancedFilterDraft.tenantId}
          onChange={(value) => updateAdvancedFilter({ tenantId: value, userId: '' })}
        >
          {tenants.map((tenant) => <option value={tenant.id} key={tenant.id}>{tenant.name || tenant.tenantKey}</option>)}
        </FilterSelect>
        <FilterSelect label="用户" value={advancedFilterDraft.userId} onChange={(value) => updateAdvancedFilter({ userId: value })}>
          {users.filter((user) => !advancedFilterDraft.tenantId || user.gatewayTenantId === advancedFilterDraft.tenantId).map((user) => (
            <option value={user.id} key={user.id}>{adminUserLabel(user)}</option>
          ))}
        </FilterSelect>
        <FilterSelect label="用户组" value={advancedFilterDraft.userGroupId} onChange={(value) => updateAdvancedFilter({ userGroupId: value })}>
          {props.data.userGroups.map((group) => <option value={group.id} key={group.id}>{group.name || group.groupKey}</option>)}
        </FilterSelect>
        <FilterSelect label="状态" value={advancedFilterDraft.status} onChange={(value) => updateAdvancedFilter({ status: value })}>
          {taskStatuses.map((status) => <option value={status} key={status}>{status}</option>)}
        </FilterSelect>
        <FilterSelect label="平台" value={advancedFilterDraft.platformId} onChange={(value) => updateAdvancedFilter({ platformId: value })}>
          {platforms.map((platform) => <option value={platform.id} key={platform.id}>{platform.internalName || platform.name}</option>)}
        </FilterSelect>
        <FilterSelect label="模型" value={advancedFilterDraft.model} onChange={(value) => updateAdvancedFilter({ model: value })}>
          {models.map((model) => <option value={model} key={model}>{model}</option>)}
        </FilterSelect>
        <FilterSelect label="类型" value={advancedFilterDraft.modelType} onChange={(value) => updateAdvancedFilter({ modelType: value })}>
          {modelTypes.map((modelType) => <option value={modelType} key={modelType}>{modelType}</option>)}
        </FilterSelect>
        <FilterSelect label="运行模式" value={advancedFilterDraft.runMode} onChange={(value) => updateAdvancedFilter({ runMode: value })}>
          <option value="production">production</option>
          <option value="simulation">simulation</option>
        </FilterSelect>
        <FilterSelect label="计费状态" value={advancedFilterDraft.billingStatus} onChange={(value) => updateAdvancedFilter({ billingStatus: value })}>
          {billingStatuses.map((status) => <option value={status} key={status}>{status}</option>)}
        </FilterSelect>
        <Label>
          API Key
          <Input
            value={advancedFilterDraft.apiKey}
            placeholder="名称、ID 或前缀"
            onChange={(event) => updateAdvancedFilter({ apiKey: event.target.value })}
          />
        </Label>
      </FormDialog>

      <FormDialog
        ariaLabel="查看管理员任务原始 JSON"
        bodyClassName="taskJsonDialogBody"
        className="taskJsonDialog"
        footer={(
          <>
            {detailSensitive === 'masked' && (
              <Button type="button" variant="outline" size="sm" disabled={!detail || detailLoading} onClick={() => setRevealConfirmOpen(true)}>
                查看完整敏感字段
              </Button>
            )}
            <Button type="button" size="sm" onClick={() => setDetail(null)}>关闭</Button>
          </>
        )}
        open={Boolean(detail)}
        title={detailSensitive === 'full' ? '任务原始 JSON（完整数据）' : '任务原始 JSON（默认脱敏）'}
        onClose={() => setDetail(null)}
        onSubmit={(event) => event.preventDefault()}
      >
        {detailError && <p className="formError">{detailError}</p>}
        {detailLoading && !detail ? <p className="mutedText">正在加载任务详情…</p> : (
          <pre className="taskJsonPreview">{detail ? JSON.stringify(detail, null, 2) : ''}</pre>
        )}
      </FormDialog>
      <ConfirmDialog
        confirmLabel="查看完整数据"
        description="完整数据可能包含用户输入、授权头或第三方返回内容，仅应在排障所需时查看。"
        loading={detailLoading}
        open={revealConfirmOpen}
        title="确认查看未脱敏任务详情？"
        onCancel={() => setRevealConfirmOpen(false)}
        onConfirm={revealSensitiveDetail}
      />
    </section>
  );
}

function FilterSelect(props: {
  children: ReactNode;
  label: string;
  value: string;
  onChange: (value: string) => void;
}) {
  return (
    <Label>
      {props.label}
      <Select value={props.value || 'all'} onChange={(event) => props.onChange(event.target.value === 'all' ? '' : event.target.value)}>
        <option value="all">全部</option>
        {props.children}
      </Select>
    </Label>
  );
}

function adminTaskHasActiveFilters(query: AdminTaskQuery) {
  return Boolean(
    query.query ||
    query.tenantId ||
    query.userId ||
    query.userGroupId ||
    query.status ||
    query.platformId ||
    query.model ||
    query.modelType ||
    query.runMode ||
    query.billingStatus ||
    query.apiKey ||
    query.createdFrom ||
    query.createdTo
  );
}

function emptyAdminTaskAdvancedFilters(): AdminTaskAdvancedFilters {
  return {
    tenantId: '',
    userId: '',
    userGroupId: '',
    status: '',
    platformId: '',
    model: '',
    modelType: '',
    runMode: '',
    billingStatus: '',
    apiKey: '',
  };
}

function adminTaskAdvancedFilters(query: AdminTaskQuery): AdminTaskAdvancedFilters {
  return {
    tenantId: query.tenantId,
    userId: query.userId,
    userGroupId: query.userGroupId,
    status: query.status,
    platformId: query.platformId,
    model: query.model,
    modelType: query.modelType,
    runMode: query.runMode,
    billingStatus: query.billingStatus,
    apiKey: query.apiKey,
  };
}

export function adminTaskAdvancedFilterCount(query: Partial<AdminTaskAdvancedFilters>) {
  const keys: Array<keyof AdminTaskAdvancedFilters> = [
    'tenantId',
    'userId',
    'userGroupId',
    'status',
    'platformId',
    'model',
    'modelType',
    'runMode',
    'billingStatus',
    'apiKey',
  ];
  return keys.filter((key) => Boolean(query[key])).length;
}

function adminUserLabel(user: ConsoleData['users'][number]) {
  const primary = user.displayName || user.username || user.userKey;
  return user.email ? `${primary} · ${user.email}` : primary;
}

function formatAdminTaskUpdatedAt(value: number | null) {
  if (!value) return '尚未刷新';
  return new Intl.DateTimeFormat('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  }).format(value);
}

export function adminTaskPagination(total: number, page: number, pageSize: number) {
  const safeTotal = Math.max(0, Math.floor(total));
  const safePageSize = Math.max(1, Math.floor(pageSize));
  const totalPages = Math.max(1, Math.ceil(safeTotal / safePageSize));
  const currentPage = Math.min(totalPages, Math.max(1, Math.floor(page)));
  return {
    totalPages,
    currentPage,
    pageStart: safeTotal ? Math.min((currentPage - 1) * safePageSize + 1, safeTotal) : 0,
    pageEnd: Math.min(currentPage * safePageSize, safeTotal),
  };
}
