"use client"

import type React from "react"
import { useCallback, useMemo, useState, useEffect } from "react"
import {
  Box,
  Stack,
  IconButton,
  TableCell,
} from "@mui/material"
import { faArrowUpRightFromSquare, faEye, faRotate, faTrash } from "@fortawesome/free-solid-svg-icons"
import {
  ActionsIconButton,
  iconButtonStyles,
} from "@/shared/theme/css"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import TableManager from "@/shared/components/table/table-manager"
import { dateFormat, formatDate } from "@/utils/format-time"
import { TrajetStyledRow } from "@/shared/sections/contract/styles"
import TableFilter from "@/shared/components/table/table-filter"
import { DEFAULT_CIRCUIT_USAGER_TABLE_HEAD } from "@/shared/_mock/_usagers"
import { useRouter } from "@/hooks/use-router"
import { paths } from "@/routes/paths"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
import UserSelector from "./userSelector"
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from "@/shared/types/common"
import ScheduleAmendment, { UsagerForAmendment } from "./schedule-amendments"
import { usePassengersCircuitStore } from "@/shared/api/stores/circuit-service/passengerscircuitStore"
import type { IPassengerList } from "@/shared/types/passenger"
import type { AddPassengersToCircuitResponse } from "@/shared/types/circuit"
import { enqueueSnackbar } from 'notistack'
import { AddButton } from "@/shared/components/table/styles"
import { useCircuitStore } from "@/shared/api/stores/circuit-service/circuitStore"

export interface UsagerSelector {
  id: string;
  prenom: string;
  nom: string;
}

export interface UsagerTableData extends AddPassengersToCircuitResponse {
  id: string;
}

const circuitUsagerConfig: TableConfig<UsagerSelector> = {
  initialData: [],
  defaultTableHead: DEFAULT_CIRCUIT_USAGER_TABLE_HEAD,
}

export default function CircuitUsager({ circuitId }: { circuitId: string }) {
  const router = useRouter()
  const { generateTrips, generateTripsLoading, canGenerateTrips } = useCircuitStore()
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [userToDelete, setUserToDelete] = useState<string | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)
  const [showScheduleAmendment, setShowScheduleAmendment] = useState(false)
  const [generateTripsDialogOpen, setGenerateTripsDialogOpen] = useState(false)
  const [generateTripsStatus, setGenerateTripsStatus] = useState<{ disabled: boolean; reason: string } | null>(null)
  const [selectedUsagerForAmendment, setSelectedUsagerForAmendment] = useState<UsagerForAmendment>({
    id: '',
    firstName: '',
    lastName: '',
  })

  const {
    loading: addPassengersLoading,
    addPassengersToCircuit,
    addedPassengers,
    getPassengersOfCircuit,
    assignCircuitToRepresentatives,
    cancelCircuitAssignmentForRepresentatives,
    removePassengerFromCircuit,
  } = usePassengersCircuitStore()

  const addedUsagersForTable = useMemo(() => {
    return addedPassengers.map(passenger => ({
      ...passenger,
      id: passenger.passengerId.toString()
    }))
  }, [addedPassengers])

  useEffect(() => {
    const loadCircuitPassengers = async () => {
      if (circuitId) {
        try {
          await getPassengersOfCircuit(circuitId)
        } catch (error: any) {
          enqueueSnackbar(error.message || 'Erreur lors du chargement des usagers du circuit', { variant: 'error' });
        }
      }
    }

    loadCircuitPassengers()
  }, [circuitId, getPassengersOfCircuit])

  const checkGenerateTripsStatus = useCallback(async () => {
    if (circuitId) {
      if(addedPassengers.length > 0){
        try {
          const status = await canGenerateTrips(circuitId)
          setGenerateTripsStatus(status)
        } catch (error: any) {
          setGenerateTripsStatus({ disabled: true, reason: error.message || 'Erreur lors de la vérification du statut de génération des trajets' })
        }
      }else{
        setGenerateTripsStatus({ disabled: true, reason: 'Aucun usager affecté au circuit' })
      }
    }
  }, [circuitId, canGenerateTrips, addedPassengers.length])

  useEffect(() => {
    checkGenerateTripsStatus()
  }, [checkGenerateTripsStatus])

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

  const handleScheduleAmendmentClick = (usager: IPassengerList) => {
    setSelectedUsagerForAmendment(usager)
    setShowScheduleAmendment(true)
  }

  const handleBackToTable = () => {
    setShowScheduleAmendment(false)
    setSelectedUsagerForAmendment({
      id: '',
      firstName: '',
      lastName: '',
    })
    // Re-check du statut lors du retour
    checkGenerateTripsStatus()
  }

  const {
    table,
    filteredData,
    filters,
    tableHead,
    handleFilterChange,
    handleResetFilters,
    dataToExport
  } = useTableManager<UsagerTableData>({
    ...circuitUsagerConfig,
    initialData: addedUsagersForTable
  })

  const renderCellContent = (columnId: string, value: any, row: AddPassengersToCircuitResponse) => {
    switch (columnId) {
      case "id":
        return row.passengerId.toString()
      case "birthDate":
        return formatDate(row.birthDate, dateFormat.isoDate)
      case "scheduleAmendment":
        return (
          <CustomTooltip title="Avenant Horaires" arrow>
            <IconButton onClick={() => handleScheduleAmendmentClick({
              id: row.passengerId.toString(),
              firstName: row.firstName,
              lastName: row.lastName,
            } as unknown as IPassengerList)} size="small" sx={{...ActionsIconButton}}>
              <FontAwesome icon={faEye} width={14} />
            </IconButton>
          </CustomTooltip>
        )
      default:
        return value || '-'
    }
  }

  const renderRow = (row: UsagerTableData) => {
    return (
      <TrajetStyledRow
        key={row.id}
        style={{ cursor: "pointer" }}
      >

        {tableHead.slice(0, -2).map((column: any) => (
          <TableCell
            key={column.id}
            align={column.align || "left"}
            sx={{ whiteSpace: "nowrap", py: column.id === "etat" ? 0.2 : table.dense ? 0.5 : 1 }}
          >
            {renderCellContent(column.id, row[column.id as keyof UsagerTableData], row)}
          </TableCell>
        ))}
        <TableCell align="center" sx={{ display: "flex" }}>
          <CustomTooltip title="Consulter usager" arrow>
            <IconButton onClick={() => openTrajetPage(row.id)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faArrowUpRightFromSquare} width={14} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Désaffecter usager" arrow>
            <IconButton onClick={() => handleDeleteDocument(row.id)} size="small" sx={ActionsIconButton}
              disabled={!row.canDelete}
            >
              <FontAwesome icon={faTrash} width={14} />
            </IconButton>
          </CustomTooltip>
          
        </TableCell>
      </TrajetStyledRow>
    )
  }

  const handleDeleteDocument = useCallback((userId: string) => {
    setUserToDelete(userId)
    setDeleteDialogOpen(true)
  }, [])

  const confirmDeleteDocument = useCallback(async () => {
    if (userToDelete) {
      setIsDeleting(true)
      try {
        const passengerId = Number.parseInt(userToDelete, 10)
        await removePassengerFromCircuit({ circuitId, passengerId })
        await cancelCircuitAssignmentForRepresentatives([passengerId])
        enqueueSnackbar('Usager désaffecté du circuit', { variant: 'success' })
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la désaffectation de l\'usager', { variant: 'error' })
      } finally {
        setDeleteDialogOpen(false)
        setUserToDelete(null)
        setIsDeleting(false)
      }
    }
  }, [userToDelete, removePassengerFromCircuit, cancelCircuitAssignmentForRepresentatives, circuitId])

  const handleUserSelection = useCallback(
    async (users: string[]) => {
      try {
        const passengersIds = users.map((id) => Number.parseInt(id, 10))

        try {
          await addPassengersToCircuit({
            circuitId: circuitId,
            passengersIds: passengersIds,
          })
        } catch (error: any) {
          enqueueSnackbar(error.message || "Échec de l'affectation des usagers au circuit", { variant: 'error' })
          return
        }

        try {
          const blockedMessages = await assignCircuitToRepresentatives({
            circuitId: circuitId,
            passengerIds: passengersIds,
          })

          if (blockedMessages && blockedMessages.length > 0) {
            try {
              await cancelCircuitAssignmentForRepresentatives(passengersIds)
            } catch (rollbackError: any) {
              enqueueSnackbar(rollbackError.message || "Rollback de l'assignation échoué", { variant: 'error' })
            }

            blockedMessages.forEach(message => {
              enqueueSnackbar(message, { variant: 'warning' })
            })
            return
          }

          enqueueSnackbar('Les usagers sont affectés avec succès', { variant: 'success' })
        } catch (error: any) {
          try {
            await cancelCircuitAssignmentForRepresentatives(passengersIds)
          } catch (rollbackError: any) {
            enqueueSnackbar(rollbackError.message || "Rollback de l'assignation échoué", { variant: 'error' })
          }

          enqueueSnackbar(error.message || "Échec de l'assignation du circuit aux représentants d'usager.", { variant: 'warning' })
        }
      } catch (error: any) {
        enqueueSnackbar(error.message || "Erreur lors de l'affectation des usagers au circuit.", { variant: 'error' })
      }
    },
    [addPassengersToCircuit, assignCircuitToRepresentatives, cancelCircuitAssignmentForRepresentatives, circuitId],
  )

  const handleGenerateTrips = useCallback(() => {
    setGenerateTripsDialogOpen(true)
  }, [])

  const handleConfirmGenerateTrips = useCallback(async () => {

    try {
      await generateTrips(circuitId)
      enqueueSnackbar("Génération des trajets effectuée avec succès", { variant: 'success' });
      setGenerateTripsDialogOpen(false);
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Erreur lors de la génération des trajets', { variant: 'error' });
    }
  }, [generateTrips, circuitId])

  if (showScheduleAmendment) {
    return (
      <ScheduleAmendment 
        onBack={handleBackToTable}
        usager={selectedUsagerForAmendment}
        circuitId={circuitId}
      />
    )
  }

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" gap="8px" py={2}>
        <UserSelector
          onUserSelection={handleUserSelection}
          loading={addPassengersLoading}
        />

        <Stack direction="row" alignItems="center" gap="8px">

   <CustomTooltip
    title={
      generateTripsStatus?.disabled
        ? generateTripsStatus.reason
        : "Générer les trajets"
    }
    arrow
    colorSchema={generateTripsStatus?.disabled ? 'warning' : 'primary'}
  >
    <span style={{ display: 'inline-block' }}>
      <AddButton 
        variant="contained" 
        onClick={handleGenerateTrips} 
        disabled={generateTripsLoading || !addedUsagersForTable.length || generateTripsStatus?.disabled}
      >
        Générer les trajets
      </AddButton>
    </span>
  </CustomTooltip>

          <Box
            sx={{
              borderLeft: 1,
              height: 30,
              borderColor: (theme) => theme.palette.text.disabled,
              mx: 1,
            }}
          />

          <CustomTooltip title="Refresh" arrow>
            <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
              <FontAwesome icon={faRotate} width={16} />
            </IconButton>
          </CustomTooltip>
          <TableFilter
            onResetFilters={handleResetFilters}
            onFilters={handleFilterChange}
            initialColumns={tableHead}
            type="document"
          />
          <ExportButton
            tooltipTitle={"Exporter"}
            type={TableType.Usager}
            filteredData={dataToExport}
            tableHead={tableHead}
          />
        </Stack>
      </Stack>
      <TableManager
        filteredData={filteredData}
        table={table}
        tableHead={tableHead}
        notFound={addedUsagersForTable.length === 0}
        filters={filters}
        onFilterChange={handleFilterChange}
        renderRow={renderRow}
        sx={{ backgroundColor: 'primary.lighter' }}
        isTrajetTable={true}
        isWithoutTabs
        loading={addPassengersLoading}
      />
      <ConfirmDialog
        open={deleteDialogOpen}
        title="Confirmation de désaffectation"
        content="Êtes-vous sûr de vouloir désaffecter cet usager du circuit ?"
        onConfirm={confirmDeleteDocument}
        onCancel={() => setDeleteDialogOpen(false)}
        confirmDisabled={isDeleting}
      />
      <ConfirmDialog
        open={generateTripsDialogOpen}
        title="Confirmation de génération des trajets"
        content="Êtes-vous sûr de vouloir générer les trajets ?"
        onConfirm={handleConfirmGenerateTrips}
        onCancel={() => setGenerateTripsDialogOpen(false)}
        confirmDisabled={generateTripsLoading}
      />
    </Box>
  )
}