import type { TabValue } from "tdesign-react";

import { useCallback, useMemo, useState } from "react";
import { DateRangePicker, Drawer, RadioGroup, Space, Tabs, Tag, Typography } from "tdesign-react";

import type { HistoryResponse, TargetMetricsResponse, TargetStatus } from "../../shared/api";

import { getTargetDisplayName } from "../utils/target";
import { subtractHours } from "../utils/time";
import { HistoryTab } from "./HistoryTab";
import { OverviewTab } from "./OverviewTab";
import { StatusDot } from "./StatusDot";

interface TargetDetailDrawerProps {
  activeTab: string;
  historyData: HistoryResponse;
  historyLoading: boolean;
  metricsData: null | TargetMetricsResponse;
  metricsLoading: boolean;
  onClose: () => void;
  onPageChange: (page: number) => void;
  onTabChange: (tab: string) => void;
  onTimeChange: (from: string, to: string) => void;
  target: null | TargetStatus;
  timeFrom: string;
  timeTo: string;
}

const TIME_SHORTCUTS = [
  { hours: 1, label: "1小时", value: "1h" },
  { hours: 6, label: "6小时", value: "6h" },
  { hours: 24, label: "24小时", value: "24h" },
  { hours: 168, label: "7天", value: "7d" },
] as const;

export function TargetDetailDrawer({
  activeTab,
  historyData,
  historyLoading,
  metricsData,
  metricsLoading,
  onClose,
  onPageChange,
  onTabChange,
  onTimeChange,
  target,
  timeFrom,
  timeTo,
}: TargetDetailDrawerProps) {
  const [activeShortcut, setActiveShortcut] = useState<string>("24h");

  const handleShortcut = useCallback(
    (value: string) => {
      const shortcut = TIME_SHORTCUTS.find((s) => s.value === value);
      if (!shortcut) return;
      const now = new Date();
      const from = subtractHours(now, shortcut.hours);
      onTimeChange(from.toISOString(), now.toISOString());
      setActiveShortcut(value);
    },
    [onTimeChange],
  );

  const handleDateRangeChange = useCallback(
    (value: Array<Date | number | string>) => {
      if (value?.length === 2) {
        onTimeChange(new Date(value[0]!).toISOString(), new Date(value[1]!).toISOString());
        setActiveShortcut("");
      }
    },
    [onTimeChange],
  );

  const isUp = target?.latestCheck?.matched;

  const dragLimits = useMemo(() => {
    const viewportWidth = window.innerWidth;
    const safeGap = 24;
    return {
      max: Math.min(1200, Math.max(360, viewportWidth - safeGap)),
      min: 360,
    };
  }, []);

  return (
    <Drawer
      attach="body"
      className="target-detail-drawer"
      footer={false}
      header={
        target ? (
          <Space align="center" size={12}>
            <StatusDot up={!!isUp} />
            <Typography.Text strong>{getTargetDisplayName(target)}</Typography.Text>
            <Tag size="small" theme="primary" variant="light-outline">
              {target.type}
            </Tag>
          </Space>
        ) : undefined
      }
      onClose={onClose}
      placement="right"
      preventScrollThrough
      showInAttachedElement={false}
      showOverlay
      size="var(--target-detail-drawer-width)"
      sizeDraggable={dragLimits}
      visible={!!target}
    >
      <Space className="full-width" direction="vertical" size={16}>
        <div className="drawer-time-controls">
          <RadioGroup
            onChange={handleShortcut}
            options={TIME_SHORTCUTS.map((s) => ({ label: s.label, value: s.value }))}
            theme="button"
            value={activeShortcut}
            variant="default-filled"
          />
          <DateRangePicker
            className="drawer-date-range"
            defaultTime={["00:00:00", "23:59:00"]}
            enableTimePicker
            format="YYYY-MM-DD HH:mm"
            mode="date"
            onChange={handleDateRangeChange}
            timePickerProps={{ format: "HH:mm", steps: [1, 1, 60] }}
            value={timeFrom && timeTo ? [timeFrom, timeTo] : undefined}
            valueType="YYYY-MM-DD HH:mm"
          />
        </div>
        <Tabs onChange={(val: TabValue) => onTabChange(String(val))} value={activeTab}>
          <Tabs.TabPanel className="tab-panel-padded" destroyOnHide={false} label="概览" value="overview">
            {target && <OverviewTab metricsData={metricsData} metricsLoading={metricsLoading} target={target} />}
          </Tabs.TabPanel>

          <Tabs.TabPanel className="tab-panel-padded" destroyOnHide={false} label="记录" lazy value="history">
            <HistoryTab historyData={historyData} historyLoading={historyLoading} onPageChange={onPageChange} />
          </Tabs.TabPanel>
        </Tabs>
      </Space>
    </Drawer>
  );
}
