"use client"

import React, { useCallback, useMemo } from "react"
import { Box, Stack, IconButton, Grid, Typography } from "@mui/material"
import { faFileExport, faPenToSquare } from "@fortawesome/free-solid-svg-icons"
import { centerFlexColumn, iconButtonStyles, tabsBorder } from "@/shared/theme/css"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType } from "@/shared/types/common"
import { getFormFieldsTripDriverAssignmentDetails } from "../../../utils/form-fields-circuit"
import { ITripDriverAssignment, ITripDriverAssignmentDetails } from "@/shared/types/circuit"
import TransportScheduleField from "@/shared/components/form/transport-schedule-field"
import { transformToWeekSchedule } from "../../../utils/schedule-converters"
import { useTripDriverAssignmentStore } from "@/shared/api/stores/circuit-service/tripDriverAssignmentStore"

const TOOLTIP_TITLES = {
  edit: "Modifier chauffeur",
  export: "Exporter",
}

interface ChauffeurFormProps {
  onEdit: (updatedTrajet: ITripDriverAssignment) => void
}

export default function NewChauffeurForm({ onEdit }: ChauffeurFormProps) {
  const { assignmentDetails } = useTripDriverAssignmentStore();

  const toITripDriverAssignmentWithNulls = (
    d: ITripDriverAssignmentDetails | null,
  ): ITripDriverAssignment | null => {
    if (!d) return null;
    const mapped: ITripDriverAssignment = {
      id: d.id,
      createdAt: d.createdAt,
      updatedAt: d.updatedAt,
      assignmentStartDate: d.assignmentStartDate,
      assignmentEndDate: d.assignmentEndDate,
      tripId: d.tripId,
      driverId: d.driverId,
      observations: d.observations,
      weeklyAssignmentSchedule: d.weeklyAssignmentSchedule,
      replacedByDriverId: 0,
      isActive: true,
    };
    return mapped;
  };

  const renderField = useCallback(
    (field: FormFieldType<ITripDriverAssignmentDetails>) => {
      return (
        <FormField
          field={field}
          value={assignmentDetails![field.name]}
          onChange={(name, value) => void 0}
          isReadOnly={true}
        />
      )
    },
    [assignmentDetails],
  )

  const memoizedFormFields = useMemo(
    () => (
      <>
        {getFormFieldsTripDriverAssignmentDetails().map((field) =>
          field.name === "weeklyAssignmentSchedule" ? (
            <React.Fragment key={field.name}>
              <Grid
                item
                lg={8}
                xl={6}
                key={field.name}
              >
                <Typography sx={{ color: (theme) => theme.palette.primary.main }}>{field.label}</Typography>
                <TransportScheduleField
                  initialSchedules={transformToWeekSchedule(assignmentDetails![field.name])}
                  onChange={(updatedSchedules) => void 0}
                  isReadOnly={true}
                />
              </Grid>
            </React.Fragment>
          ) : (
            <Grid
              sx={centerFlexColumn}
              item
              xs={12}
              sm={6}
              key={field.name}
            >
              {renderField(field)}
            </Grid>
          ),
        )}
      </>
    ),
    [assignmentDetails, renderField],
  )


  return (
    <Box pt={4} sx={tabsBorder}>
        <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" gap="8px" py={1}>
          <CustomTooltip title={TOOLTIP_TITLES.edit} arrow>
            <IconButton onClick={() => { const v = toITripDriverAssignmentWithNulls(assignmentDetails); if (v) onEdit(v); }} size="small" sx={iconButtonStyles}>
              <FontAwesome icon={faPenToSquare} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title={TOOLTIP_TITLES.export} arrow>
            <IconButton size="small" sx={iconButtonStyles}>
              <FontAwesome icon={faFileExport} width={16} />
            </IconButton>
          </CustomTooltip>
        </Stack>

        <Grid container spacing={6}>
          {memoizedFormFields}
        </Grid>
    </Box>
  )
}
