'use client';
import * as React from 'react';
import {
  Box,
  Stack,
  Typography,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Switch,
  Button,
  Chip,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import dayjs from 'dayjs';

import type { VehicleAnomalyConfig, ConfigKey } from '@/shared/_mock/flottes/_anomaly-config';
import { useVehicleConfig } from '../hooks/use-vehicle-config';
import ApplyToOthersDialog from '../components/apply-config-to-other-dialog';
import ScheduleDetailsEditor from '../components/schedule-details-editor';
import { RoadMapStyledTimePicker, StyledTextField } from '@/shared/theme/css';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

type VRequired = Required<VehicleAnomalyConfig>;

type Props = { vehicleId: string | undefined };

const LABELS: Record<ConfigKey, string> = {
  multipleUsePerDay: 'Utilisation multiple par jour',
  fuelOutsideServiceArea: 'Plein hors zone de service',
  fuelOutsideServiceHours: 'Plein hors horaires de service',
  abnormallyHighVolume: 'Volume anormalement élevé',
  cardUsedDuringStop: 'Carte utilisée pendant arrêt',
  useWithoutPlannedTrip: 'Utilisation sans trajet prévu',
  repeatedStationShortInterval: 'Station répétée à court intervalle',
  abnormalConsumption: 'Consommation anormale',
  useOutsideTrip: 'Utilisation hors trajet',

  km_deviation: 'Écart de consommation anormale',
  avg_per_km: 'Moyenne consommation par km',
};

const ORDER: ConfigKey[] = [
  'multipleUsePerDay',
  'fuelOutsideServiceArea',
  'fuelOutsideServiceHours',
  'abnormallyHighVolume',
  'cardUsedDuringStop',
  'useWithoutPlannedTrip',
  'repeatedStationShortInterval',
  'abnormalConsumption',
  'useOutsideTrip',

  'km_deviation',
  'avg_per_km',
];

export default function VehicleConfigView({ vehicleId }: Props) {
  const { loading, saving, config, setEnabled, updateDetails, saveAll, refresh, applyToOthers } =
    useVehicleConfig(vehicleId);

  const cfg = config as VRequired;

  const [applyOpen, setApplyOpen] = React.useState(false);
  const [applySource, setApplySource] = React.useState<ConfigKey | null>(null);

  const openApply = (source: ConfigKey) => {
    setApplySource(source);
    setApplyOpen(true);
  };
  const handleApplyConfirm = (targets: ConfigKey[]) => {
    if (!applySource || targets.length === 0) return;
    applyToOthers(applySource, targets, { copyEnabled: true });
    setApplyOpen(false);
  };
  return (
    <Box p={2}>
      <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
        <Stack direction="row" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h6">Configuration d’anomalies · Véhicule {vehicleId}</Typography>
        </Stack>

        {/* Bloc Carburant */}
        <Box
          p={2}
          mb={2}
          sx={{
            borderRadius: 2,
            border: '1px solid',
            borderColor: 'divider',
            bgcolor: 'action.hover',
          }}
        >
          <Typography fontWeight={600} mb={1}>
            Configuration Carburant
          </Typography>
          <Stack>
            {ORDER.slice(0, 9).map((key) => {
              const item = cfg[key];
              return (
                <Accordion key={key} disableGutters>
                  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                    <Stack
                      direction="row"
                      alignItems="center"
                      justifyContent="space-between"
                      sx={{ width: '100%' }}
                    >
                      <Stack direction="row" spacing={1} alignItems="center">
                        <Switch
                          size="small"
                          checked={item.enabled}
                          onClick={(e) => e.stopPropagation()}
                          onChange={(e) => setEnabled(key, e.target.checked)}
                        />
                        <Typography>{LABELS[key]}</Typography>
                        <ConditionalComponent isValid={!item.enabled}>
                          <Chip size="small" label="Inactif" />
                        </ConditionalComponent>{' '}
                      </Stack>
                    </Stack>
                  </AccordionSummary>
                  <AccordionDetails>
                    <ConfigFields
                      k={key}
                      onChange={(f, v) => updateDetails(key as any, f as any, v as any)}
                      values={item.details as any}
                      onApplyToOthers={() => openApply(key)}
                    />
                  </AccordionDetails>
                </Accordion>
              );
            })}
          </Stack>
        </Box>

        {/* Bloc Kilométrage */}
        <Box
          p={2}
          sx={{
            borderRadius: 2,
            border: '1px solid',
            borderColor: 'divider',
            bgcolor: 'warning.lighter',
          }}
        >
          <Typography fontWeight={600} mb={1}>
            Configuration Kilométrage
          </Typography>
          <Stack>
            {ORDER.slice(9).map((key) => {
              const item = cfg[key];
              return (
                <Accordion key={key} disableGutters>
                  <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                    <Stack
                      direction="row"
                      alignItems="center"
                      justifyContent="space-between"
                      sx={{ width: '100%' }}
                    >
                      <Stack direction="row" spacing={1} alignItems="center">
                        <Switch
                          size="small"
                          checked={item.enabled}
                          onClick={(e) => e.stopPropagation()}
                          onChange={(e) => setEnabled(key, e.target.checked)}
                        />
                        <Typography>{LABELS[key]}</Typography>
                        <ConditionalComponent isValid={!item.enabled}>
                          <Chip size="small" label="Inactif" />
                        </ConditionalComponent>{' '}
                      </Stack>
                    </Stack>
                  </AccordionSummary>
                  <AccordionDetails>
                    <ConfigFields
                      k={key}
                      onChange={(f, v) => updateDetails(key as any, f as any, v as any)}
                      values={item.details as any}
                      onApplyToOthers={() => openApply(key)}
                    />
                  </AccordionDetails>
                </Accordion>
              );
            })}
          </Stack>
        </Box>

        <Stack direction="row" justifyContent="flex-end" spacing={1} m={2}>
          <Button variant="contained" onClick={saveAll} disabled={saving}>
            Sauvegarder les modifications
          </Button>
        </Stack>
        <ApplyToOthersDialog
          open={applyOpen}
          onClose={() => setApplyOpen(false)}
          sourceKey={applySource}
          onApplySelectedKeys={handleApplyConfirm}
        />
      </LocalizationProvider>
    </Box>
  );
}

function ConfigFields({
  k,
  values,
  onChange,
  onApplyToOthers,
}: {
  k: ConfigKey;
  values: any;
  onChange: (field: string, value: any) => void;
  onApplyToOthers?: () => void;
}) {
  return (
    <Stack spacing={2}>
      <ConditionalComponent isValid={k === 'multipleUsePerDay'}>
        <StyledTextField
          label="Limite d'utilisation par jour"
          size="small"
          type="number"
          value={values.limitPerDay ?? 1}
          onChange={(e) => onChange('limitPerDay', Number(e.target.value))}
          fullWidth
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={k === 'fuelOutsideServiceArea'}>
        <StyledTextField
          label="Rayon zone service (km)"
          size="small"
          type="number"
          value={values.radiusKm ?? 50}
          onChange={(e) => onChange('radiusKm', Number(e.target.value))}
          fullWidth
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={k === 'fuelOutsideServiceHours'}>
        <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
          <RoadMapStyledTimePicker
            label="Heure début :"
            value={values.serviceStartHour ?? null}
            onChange={(val) =>
              onChange('serviceStartHour', val ? dayjs(val).format('HH:mm') : null)
            }
            views={['hours', 'minutes']}
            format="HH:mm"
            ampm={false}
            slotProps={{
              textField: {
                fullWidth: true,
                size: 'small',
                placeholder: "Sélectionner l'heure",
                InputLabelProps: { shrink: true },
              },
            }}
          />

          <RoadMapStyledTimePicker
            label="Heure fin :"
            value={values.serviceEndHour ?? null}
            onChange={(val) => onChange('serviceEndHour', val ? dayjs(val).format('HH:mm') : null)}
            views={['hours', 'minutes']}
            format="HH:mm"
            ampm={false}
            slotProps={{
              textField: {
                fullWidth: true,
                size: 'small',
                placeholder: "Sélectionner l'heure",
                InputLabelProps: { shrink: true },
              },
            }}
          />
        </Stack>
      </ConditionalComponent>

      <ConditionalComponent isValid={k === 'abnormallyHighVolume'}>
        <StyledTextField
          label="Capacité réservoir (L)"
          size="small"
          type="number"
          value={values.tankCapacityL ?? 60}
          onChange={(e) => onChange('tankCapacityL', Number(e.target.value))}
          fullWidth
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={k === 'abnormalConsumption'}>
        <StyledTextField
          label="Tolérance consommation (%)"
          size="small"
          type="number"
          value={values.tolerancePercent ?? 10}
          onChange={(e) => onChange('tolerancePercent', Number(e.target.value))}
          fullWidth
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={k === 'km_deviation'}>
        <StyledTextField
          label="Tolérance (%)"
          size="small"
          type="number"
          value={values.tolerancePercent ?? 10}
          onChange={(e) => onChange('tolerancePercent', Number(e.target.value))}
          fullWidth
        />
      </ConditionalComponent>
      <Stack direction="row" justifyContent="flex-end">
        <Button
          size="small"
          variant="contained"
          color="primary"
          onClick={onApplyToOthers}
          startIcon={<ContentCopyIcon fontSize="small" />}
        >
          Appliquer à d’autres
        </Button>
      </Stack>

      <ScheduleDetailsEditor
        value={{
          startDate: values.startDate ?? dayjs().format('YYYY-MM-DD'),
          endDate: values.endDate ?? dayjs().add(30, 'day').format('YYYY-MM-DD'),
          days: values.days ?? [1, 2, 3, 4, 5, 6, 0],
          startHour: values.startHour ?? '00:00',
          endHour: values.endHour ?? '23:59',
        }}
        onChange={(patch) => {
          if ('startDate' in patch) onChange('startDate', patch.startDate);
          if ('endDate' in patch) onChange('endDate', patch.endDate);
          if ('days' in patch) onChange('days', patch.days);
          if ('startHour' in patch) onChange('startHour', patch.startHour);
          if ('endHour' in patch) onChange('endHour', patch.endHour);
        }}
      />
    </Stack>
  );
}
