import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { TableCell } from "@mui/material"
import { TrajetStyledRow } from "../../contract/styles"
import { TableColumn } from "@/shared/types/common"
import { useCallback, useEffect, useState } from "react"
import dayjs from "dayjs"
import { Box, Stack } from "@mui/system"
import { LocalizationProvider } from "@mui/x-date-pickers"
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"
import { faClock, faUser } from "@fortawesome/free-solid-svg-icons"

import FontAwesome from "@/shared/components/fontawesome"
import SvgColor from "@/shared/components/svg-color"
import { StyledTimePicker } from "@/shared/theme/css"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { TripPointDetails } from "@/shared/types/circuit"
import { fetchAddressFromLatLng } from "../utils/maps-utils"
import { enqueueSnackbar } from "notistack"

interface SortableTrajetRowProps {
    row: TripPointDetails
    tableHead: TableColumn[]
    editingHoraireId: string | null
    setEditingHoraireId: (id: string | null) => void
    handleCommitHoraireChange: (rowId: string, newValue: dayjs.Dayjs | null) => void
}

export function SortableTrajetRow({
    row,
    tableHead,
    editingHoraireId,
    setEditingHoraireId,
    handleCommitHoraireChange,
}: SortableTrajetRowProps) {
    const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: row.id })
    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    }
    const [address, setAddress] = useState<string>("");

    useEffect(() => {
        const coords = row.passengerDetailsTrip?.startCoordinates;
        if (coords && coords.latitude && coords.longitude) {
            fetchAddressFromLatLng(coords.latitude, coords.longitude)
                .then(setAddress)
                .catch((error) => {
                    enqueueSnackbar("Erreur lors de la récupération de l'adresse :"+error, { variant: "error" });
                    setAddress("");
                });
        } else {
            setAddress("");
        }
    }, [row.passengerDetailsTrip?.startCoordinates]);

    const renderCellContent = useCallback(
        (columnId: string, value: any, row: TripPointDetails) => {
            switch (columnId) {
                case "km":
                    return row.routeToNext?.distance
                case "tps":
                    return row.routeToNext?.duration
                case "gps":
                    return "[" + row.passengerDetailsTrip.startCoordinates.latitude + ", " + row.passengerDetailsTrip.startCoordinates.longitude + "]"
                case "nom":
                    return (
                        <Stack direction="column" spacing={1} alignItems="flex-start">
                            <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
                                <ConditionalComponent isValid={!!row.passengerDetailsTrip?.establishmentName}>
                                    <SvgColor
                                        src={"/assets/icons/form/ic_building.svg"}
                                        sx={{ color: "primary.main", width: 12, height: 12 }}
                                    />
                                    {row.passengerDetailsTrip?.establishmentName}
                                </ConditionalComponent>
                                <ConditionalComponent isValid={!!row.passengerDetailsTrip?.fullName}>
                                    <FontAwesome icon={faUser} width={12} color="primary.main" />
                                    {row.passengerDetailsTrip?.fullName}
                                </ConditionalComponent>
                            </Box>
                            <Box>{address || ""}</Box>
                        </Stack>
                    )
                case "horaire":
                    value = row.passengerDetailsTrip?.pickupTime
                    const canEditHoraire = row.passengerDetailsTrip?.establishmentName && row.passengerDetailsTrip?.pickupTime 
                    if (editingHoraireId === row.id) {
                        return (
                            <LocalizationProvider
                                dateAdapter={AdapterDayjs}
                                localeText={{
                                    okButtonLabel: "Confirmer",
                                    cancelButtonLabel: "Annuler",
                                }}
                            >
                                <StyledTimePicker
                                    value={value ? dayjs(value, "HH:mm:ss") : null}
                                    onAccept={(v) => {
                                        handleCommitHoraireChange(row.id, v as dayjs.Dayjs | null)
                                    }}
                                    onClose={() => {
                                        handleCommitHoraireChange(row.id, null)
                                    }}
                                    views={["hours", "minutes", "seconds"]}
                                    format="HH:mm:ss"
                                    slots={{
                                        openPickerIcon: () => <FontAwesome icon={faClock} sx={{ color: "primary.main" }} />,
                                    }}
                                    slotProps={{
                                        actionBar: { actions: ["accept", "cancel"] },
                                        textField: {
                                            variant: "standard",
                                            size: "small",
                                        },
                                    }}
                                />
                            </LocalizationProvider>
                        )
                    }
                    return (
                        <Box 
                            sx={{ 
                                cursor: canEditHoraire ? "pointer" : "not-allowed", 
                                minWidth: 90,
                                opacity: 1
                            }} 
                            onDoubleClick={() => {
                                if (canEditHoraire) {
                                    setEditingHoraireId(row.id);
                                }
                            }}
                        >
                            {value || "--:--"}
                        </Box>
                    )
                default:
                    return value
            }
        },
        [editingHoraireId, handleCommitHoraireChange, setEditingHoraireId, address],
    )
    return (
        <TrajetStyledRow style={style} ref={setNodeRef}>
            {tableHead.map((column: any) => (
                <TableCell
                    {...(column.id !== "horaire" ? attributes : {})}
                    {...(column.id !== "horaire" ? listeners : {})}
                    key={column.id}
                    align={column.align || "left"}
                    sx={{
                        whiteSpace: "nowrap",
                        py: 1,
                        cursor: column.id !== "horaire" ? "grab" : "default",
                    }}
                >
                    {renderCellContent(column.id, row[column.id as keyof TripPointDetails], row)}
                </TableCell>
            ))}
        </TrajetStyledRow>
    )
}
