"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 } 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 { useTheme } from "@mui/material/styles"
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 { usePassengerStore } from "@/shared/api/stores/passengerStore"
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 convertPassengerToUsager = (passenger: IPassengerList): UsagerSelector => ({
  id: passenger.id,
  prenom: passenger.firstName,
  nom: passenger.lastName,
})

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

export default function CircuitUsager( {circuitId}: {circuitId: string} ) {
  const router = useRouter()
  const { generateTrips, generateTripsLoading } = useCircuitStore()
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [userToDelete, setUserToDelete] = useState<string | null>(null)
  const [selectedUsers, setSelectedUsers] = useState<string[]>([])
  const [showScheduleAmendment, setShowScheduleAmendment] = useState(false)
  const [generateTripsDialogOpen, setGenerateTripsDialogOpen] = useState(false)
  const [selectedUsagerForAmendment, setSelectedUsagerForAmendment] = useState<UsagerForAmendment>({
    id: '',
    firstName: '',
    lastName: '',
  })
  const { 
    passengers, 
    loading: passengersLoading, 
    error: passengersError, 
    searchPassengers 
  } = usePassengerStore()

  const { 
    loading: addPassengersLoading, 
    error: addPassengersError, 
    addPassengersToCircuit,
    addedPassengers,
    getPassengersOfCircuit
  } = usePassengersCircuitStore()

  const usagers = useMemo(() => {
    return passengers.map(convertPassengerToUsager)
  }, [passengers])

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

  useEffect(() => {
    const loadPassengers = async () => {
      try {
        await searchPassengers({
          page: 0,
          size: 100,
          sortBy: 'lastName',
          sortDir: 'asc'
        })
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors du chargement des passagers', { variant: 'error' });
      }
    }

    loadPassengers()
  }, [searchPassengers])

  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 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: '',
    })
  }

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleDelete,
  } = 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 "address":
        return row.address[0] || '-'
      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>
    
        </TableCell>
      </TrajetStyledRow>
    )
  }

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

  const confirmDeleteDocument = useCallback(() => {
    if (userToDelete) {
      setSelectedUsers((prevUsers) => prevUsers.filter((userId) => userId !== userToDelete))
      setDeleteDialogOpen(false)
      setUserToDelete(null)
    }
  }, [userToDelete])

  const availableUsers = useMemo(() => {
    return filteredData.filter((user) => !selectedUsers.includes(user.id))
  }, [filteredData, selectedUsers])

  const handleUserSelection = useCallback(async (users: string[]) => {
    try {
      await addPassengersToCircuit({
        circuitId: circuitId,
        passengersIds: users.map(id => parseInt(id, 10))
      })
      
      setSelectedUsers(users)
      
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Erreur lors de l\'ajout des usagers au circuit', { variant: 'error' });
    }
  }, [addPassengersToCircuit, circuitId])


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

  const handleConfirmGenerateTrips = useCallback(async () => {

    try {
      await generateTrips(circuitId)
      setGenerateTripsDialogOpen(false)
      enqueueSnackbar("Génération des trajets effectuée avec succès", { variant: 'success' });
    } 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 
          users={usagers} 
          selectedUsers={selectedUsers} 
          onUserSelection={handleUserSelection}
          loading={passengersLoading || addPassengersLoading}
        />        

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

          <CustomTooltip title={"Générer les trajets"} arrow>
            <AddButton variant="contained" onClick={handleGenerateTrips} disabled={generateTripsLoading || !addedUsagersForTable.length}>
              Générer les trajets
            </AddButton>
          </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)}
      />
      <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)}
      />
    </Box>
  )
}