"use client"
import { useEffect, useState } from "react"
import TableCell from "@mui/material/TableCell"
import { useTheme } from "@mui/material/styles"
import type { TableColumn } from "@/shared/types/common"
import { TrajetStyledRow } from "@/shared/sections/contract/styles"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { IconButton, List, ListItem, ListItemIcon, ListItemText } from "@mui/material"
import FontAwesome from "@/shared/components/fontawesome"
import { faArrowUpRightFromSquare, faEye } from "@fortawesome/free-solid-svg-icons"
import { ActionsIconButton, PassengerCircuitStatusChip } from "@/shared/theme/css"
import { useRouter } from "@/hooks/use-router"
import { paths } from "@/routes/paths"
import UsagerDetailsDialog from "./usager-details-dialog"
import { PassengerInfo, SensTrip, TripCircuitDTO, tripStateOptions } from "@/shared/types/circuit"
import { getLabel } from "@/shared/_mock"
import { dateFormat, formatDate } from "@/utils/format-time"

type Props = {
  handleEditContract: (contrat: TripCircuitDTO) => void
  handleDetailsContract: (id: string) => void
  row: TripCircuitDTO
  dense: boolean
  columns: TableColumn[]
}

export default function TrajetTableRow({
  dense,
  row,
  handleEditContract,
  handleDetailsContract,
  columns,
}: Props) {
  const theme = useTheme()
  const router = useRouter()
  const [openDialog, setOpenDialog] = useState(false)
  const [selectedUsager, setSelectedUsager] = useState<PassengerInfo | null>(null)


  const openTrajetPage = (id: string) => {
    router.push(`${paths.dashboard.exploitation.circuitUsager.trajet}?id=${id}`)
  }

  const handleOpenUsagerDetails = (usager: PassengerInfo) => {
    setSelectedUsager(usager)
    setOpenDialog(true)
  }

  const handleCloseDialog = () => {
    setOpenDialog(false)
    setSelectedUsager(null)
  }

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "tripState":
        return <PassengerCircuitStatusChip label={getLabel(value, tripStateOptions)} status={value} theme={theme} size="small" />
      case "createdAt":
      case "customizedDate":
        return formatDate(value, dateFormat.isoDate) || '-'
      case "kmEtTemps":
        return row.distanceKm + "km /" + row.duration
      case "establishemntName":
        if (row.tripCircuitDays && row.tripCircuitDays.length > 0) {
          const establishmentDay = row.tripCircuitDays.find(day => day.establishmentInfoTrip)
          return establishmentDay?.establishmentInfoTrip?.establishmentName || '-'
        }
        return '-'
      case "passengerInfo":
        return (
          <List dense sx={{ p: 0 }}>
            {value.map((usager: any, index: number) => (
              <ListItem key={index} sx={{ p: 0, mb: index < value.length - 1 ? 0.5 : 0 }}>
                <ListItemText primary={usager.name} sx={{ m: 0 }} />
                <ListItemIcon sx={{ minWidth: "auto", ml: 1 }}>
                  <CustomTooltip title={"Détails usager"}>
                    <IconButton onClick={() => handleOpenUsagerDetails(usager)} size="small">
                      <FontAwesome icon={faEye} width={14} />
                    </IconButton>
                  </CustomTooltip>
                </ListItemIcon>
              </ListItem>
            ))}
          </List>
        )
      case "sensTrip":
        return value === SensTrip.DEPARTURE ? "Aller" : "Retour"
      default:
        return value || '-'
    }
  }

  return (
    <>
      <TrajetStyledRow  style={{ cursor: "pointer" }}>
        {columns.slice(0, -1).map((column: any) => (
          <TableCell
            onDoubleClick={() => handleDetailsContract(row.id)}
            key={column.id}
            align={column.align || "left"}
            sx={{ whiteSpace: "nowrap", py: column.id === "etat" ? 0.2 : dense ? 0.5 : 1 }}
          >
            {renderCellContent(column.id, row[column.id as keyof TripCircuitDTO])}
          </TableCell>
        ))}
        <TableCell align="center">
          <CustomTooltip title={"Consulter trajet"} arrow>
            <IconButton onClick={() => openTrajetPage(row.id)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faArrowUpRightFromSquare} width={14} />
            </IconButton>
          </CustomTooltip>
        </TableCell>
      </TrajetStyledRow>

      <UsagerDetailsDialog 
        open={openDialog} 
        onClose={handleCloseDialog} 
        usager={selectedUsager} 
      />
    </>
  )
}
