import {
  Group,
  Text,
  Grid,
  Button,
  Table,
  SegmentedControl,
  ScrollArea,
  HoverCard,
  Stack,
  Divider
} from '@tidbcloud/uikit'
import moment from 'moment'
import React, { useEffect, useMemo, useState } from 'react'

import { EntityClusterDowntime } from 'apiClient/services/devops/interface'

interface TimelineTableProps {
  month: string
  downtimeList: EntityClusterDowntime[]
  onIncludeFakeChange: (includeFake: boolean) => void
}

interface DowntimeData {
  [day: number]: {
    count: number
    items: EntityClusterDowntime[]
  }
}

const DowntimeTimeline: React.FC<
  React.PropsWithChildren<TimelineTableProps>
> = ({ month, downtimeList, onIncludeFakeChange }) => {
  const daysInMonth = moment(month, 'YYYY/M').daysInMonth()
  const [selectedDay, setSelectedDay] = useState<number>(1)
  const [includeFake, setIncludeFake] = useState(false)

  useEffect(() => {
    onIncludeFakeChange(includeFake)
  }, [includeFake, onIncludeFakeChange])

  const downtimeData = useMemo(() => {
    const data: DowntimeData = {}
    downtimeList.forEach((item) => {
      const day = moment.unix(Number(item.timestamp)).utc().date()
      if (!data[day]) {
        data[day] = { count: 0, items: [] }
      }
      data[day].count++
      data[day].items.push(item)
    })
    return data
  }, [downtimeList])
  const filteredData = downtimeData[selectedDay]?.items || []

  const renderTimelineDay = (day: number) => {
    const downtimeCount = downtimeData[day]?.count || 0
    const color = downtimeCount > 0 ? 'red' : 'teal'
    const width = selectedDay === day ? 24 : 14
    return (
      <Grid.Col span="auto" key={day}>
        <HoverCard shadow="md" withArrow>
          <HoverCard.Target>
            <Button
              size="compact-xs"
              fullWidth
              radius="xs"
              color={color}
              onClick={() => setSelectedDay(day)}
              styles={(theme) => ({
                root: {
                  width: width,
                  height: 35,
                  padding: 0
                }
              })}
            >
              {selectedDay === day ? '*' : ''}
            </Button>
          </HoverCard.Target>
          <HoverCard.Dropdown>
            <Text size="sm" fw={700}>
              {month}/{day}
            </Text>
            <Text size="sm">
              has <b>{downtimeCount} </b> minutes downtime
            </Text>
          </HoverCard.Dropdown>
        </HoverCard>
      </Grid.Col>
    )
  }

  return (
    <div>
      {/* Timeline */}
      <Group justify="space-between">
        <Stack gap={4}>
          <Grid gutter={4}>
            {Array.from({ length: daysInMonth }, (_, i) =>
              renderTimelineDay(i + 1)
            )}
          </Grid>
          <Grid gutter={5}>
            <Grid.Col span="content">
              <Text size="xs" c="dimmed">
                {month}/1
              </Text>
            </Grid.Col>
            <Grid.Col span="auto">
              <Divider size="xs" my="xs" />
            </Grid.Col>
            <Grid.Col span="content">
              <Text size="xs" c="dimmed">
                {month}/{daysInMonth}
              </Text>
            </Grid.Col>
          </Grid>
        </Stack>
        <SegmentedControl
          value={includeFake ? 'show' : 'hide'}
          onChange={(value) => setIncludeFake(value === 'show')}
          data={[
            { label: 'Show Fake', value: 'show' },
            { label: 'Hide Fake', value: 'hide' }
          ]}
          size="sm"
          color="blue"
        />
      </Group>

      {/* Table */}
      <br />
      <ScrollArea style={{ height: 500 }} type="always">
        <Table highlightOnHover striped>
          <thead>
            <tr>
              <th>Downtime(UTC)</th>
              <th>Fake</th>
              <th>Comment</th>
            </tr>
          </thead>
          <tbody>
            {filteredData.length > 0 ? (
              filteredData.map((item, idx) => (
                <tr key={idx}>
                  <td>
                    {moment
                      .unix(Number(item.timestamp))
                      .utc()
                      .format('YYYY-MM-DD HH:mm:ss')}
                  </td>
                  <td>{item.fake ? 'Yes' : 'No'}</td>
                  <td>{item.comment || '-'}</td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={4}>No data for this day</td>
              </tr>
            )}
          </tbody>
        </Table>
      </ScrollArea>
    </div>
  )
}

export default DowntimeTimeline
