"use client"
import TableCell from "@mui/material/TableCell"
import Button from "@mui/material/Button"
import CircularProgress from "@mui/material/CircularProgress"
import SvgColor from "@/shared/components/svg-color"

import type { TableColumn } from "@/shared/types/common"
import { ExportTab, IExport } from "@/shared/types/export"
import { ContratStyledRow, getStatusColor, StatusChip } from "@/shared/sections/contract/styles"
import { dateFormat, formatDate } from "@/utils/format-time"
import { _EXPORT_OPTION_STATUT } from "@/shared/_mock/_export"
import { useState } from "react"
import { useTheme } from '@mui/material/styles';
import { getLabel } from '@/shared/_mock';
import { StatusChipExport } from "@/shared/theme/css"
import { BinaryQuestion } from "@/shared/types/trajet"
import { _BINARY_Qst } from "@/shared/_mock/_trajets"
import ConditionalComponent from '../../../components/table/ConditionalComponent';

type Props = {
  handleDownloadExport: (exportItem: IExport) => void
  selected: boolean
  row: IExport
  onSelectRow: VoidFunction
  columns: TableColumn[]
}

const TOOLTIP_TITLES = {
  edit: "Modifier export",
  duplicate: "Copier export",
  active: "Export actif",
  inactive: "Export inactif",
}

export default function ExportTableRow({
  row,
  handleDownloadExport,
  selected,
  onSelectRow,
  columns,
}: Props) {
  const [isDownloading, setIsDownloading] = useState(false)
  const theme = useTheme();

  const handleDownload = async () => {
    try {
      setIsDownloading(true)
      await handleDownloadExport(row)
    } finally {
      setTimeout(() => {
        setIsDownloading(false)
      }, 1000)
    }
  }

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "startTime":
      case "endTime":
        return formatDate(value, dateFormat.isoDate)
      case "exportFilesStatus":
        return (
          <StatusChipExport
            status={value as ExportTab}
            label={getLabel(value, _EXPORT_OPTION_STATUT)}
            theme={theme}
            size="small"
          />
        )
      case "downloaded":
        return (
          <StatusChip
            status={value as BinaryQuestion}
            label={getLabel(value, _BINARY_Qst)}
            theme={theme}
            size="small"
          />
        )
      default:
        return value
    }
  }

  return (
    <ContratStyledRow hover selected={selected} style={{ cursor: "pointer" }}>

      {columns
        .filter((column) => column.id !== "isActive")
        .map((column: any, index: number) => (
          <TableCell
            key={column.id}
            align={column.align}
            sx={{ whiteSpace: "nowrap",
              ...(index === 0 && {
                position: "relative",
              }),
              py: column.id === "status" ? 0 : "inherit" }}
          >
            <ConditionalComponent
              isValid={index === 0}
            >
              <SvgColor
                src="/assets/icons/ic_border.svg"
                sx={{ position: "absolute", top: 0, left: -4, height: "100%", color: getStatusColor(row.exportFilesStatus) }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IExport])}
          </TableCell>
        ))}

      <TableCell align="right" sx={{ px: 1, whiteSpace: "nowrap" }}>
        <Button
          variant="contained"
          size="small"
          disabled={row.exportFilesStatus !== ExportTab.COMPLETED || isDownloading}
          onClick={handleDownload}
          startIcon={isDownloading ? <CircularProgress size={20} color="inherit" /> : null}
          sx={{
            backgroundColor: "#212B36",
            "&:hover": {
              backgroundColor: "#454F5B",
            },
          }}
        >
          {isDownloading ? "Téléchargement..." : "Retélécharger"}
        </Button>
      </TableCell>
    </ContratStyledRow>
  )
}