"use client"
import TableCell from "@mui/material/TableCell"
import Chip from "@mui/material/Chip"
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, ExportFilesStatus } from "@/shared/types/export"
import { ContratStyledRow, StatusChip } from "@/shared/sections/contract/styles"
import { dateFormat, formatDate, formatDateTime } 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 ConditionalComponent from '../../../components/table/ConditionalComponent';

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


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 mapExportStatus = (status: ExportFilesStatus): ExportTab => {
    switch (status) {
      case ExportFilesStatus.DONE:
        return ExportTab.COMPLETED
      case ExportFilesStatus.IN_PROGRESS:
        return ExportTab.IN_PROGRESS
      case ExportFilesStatus.FAILED:
        return ExportTab.FAILED
      default:
        return ExportTab.ALL
    }
  }

  const getExportStatusColor = (status: ExportFilesStatus): string => {
    switch (status) {
      case ExportFilesStatus.DONE:
        return '#36B37E'
      case ExportFilesStatus.IN_PROGRESS:
        return '#F9B90B'
      case ExportFilesStatus.FAILED:
        return '#FF3434'
      default:
        return '#F9B90B'
    }
  }

  const formatBytes = (bytes: number): string => {
    if (!bytes || bytes < 0) return '0 B'
    const units = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    const num = bytes / Math.pow(1024, isFinite(i) ? i : 0)
    return `${num.toFixed(num >= 100 ? 0 : num >= 10 ? 1 : 2)} ${units[isFinite(i) ? i : 0]}`
  }

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "startTime":
        return formatDateTime(value, 'DD MMM YYYY HH:mm')
      case "endTime":
        return formatDate(value, dateFormat.isoDate)
      case "downloadDate":
        return value ? formatDateTime(value, 'DD MMM YYYY HH:mm') : ''
      case "filePath":
        return String(value || "").split(/[\\/]/).pop()
      case "exportFilesStatus":
        return (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <StatusChipExport
              status={mapExportStatus(value as ExportFilesStatus)}
              label={getLabel(value, _EXPORT_OPTION_STATUT)}
              theme={theme}
              size="small"
            />
            {(value as ExportFilesStatus) === ExportFilesStatus.IN_PROGRESS && (
              <CircularProgress size={16} />
            )}
          </span>
        )
      case "downloaded":
        return (
          <Chip
            label={value ? 'Oui' : 'Non'}
            color={value ? 'success' : 'error'}
            size="small"
            sx={{ color: '#fff', fontWeight: 600 }}
          />
        )
      case "fileSize":
        return formatBytes(Number(value) || 0)
      case "user":
        return value || ""
      default:
        return value
    }
  }

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

      {columns
        .filter((column) => column.id !== "isActive" && column.id !== "classExported" && column.id !== "endTime")
        .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: getExportStatusColor(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 !== ExportFilesStatus.DONE || isDownloading}
          onClick={handleDownload}
          startIcon={isDownloading ? <CircularProgress size={20} color="inherit" /> : null}
          sx={{
            backgroundColor: "#212B36",
            "&:hover": {
              backgroundColor: "#454F5B",
            },
          }}
        >
          {isDownloading
            ? "Téléchargement..."
            : row.downloaded
              ? "Retélécharger"
              : "Télécharger"}
        </Button>
      </TableCell>
    </ContratStyledRow>
  )
}
