import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import moment from 'moment';
import 'moment/locale/fr';
import { DayPickerRangeController } from 'react-dates';
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Switch from '@mui/material/Switch';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import Tooltip from '@mui/material/Tooltip';
import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Alert from '@mui/material/Alert';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';

import AccessTimeRoundedIcon from '@mui/icons-material/AccessTimeRounded';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
import TuneRoundedIcon from '@mui/icons-material/TuneRounded';
import NightsStayRoundedIcon from '@mui/icons-material/NightsStayRounded';
import HourglassEmptyRoundedIcon from '@mui/icons-material/HourglassEmptyRounded';
import SwapHorizRoundedIcon from '@mui/icons-material/SwapHorizRounded';
import NavigateBeforeRoundedIcon from '@mui/icons-material/NavigateBeforeRounded';
import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded';
import EventBusyRoundedIcon from '@mui/icons-material/EventBusyRounded';
import DeleteRoundedIcon from '@mui/icons-material/DeleteRounded';

import { getBlackouts, addBlackout, deleteBlackout } from '../hooks/useApi';

/* ── Constants ───────────────────────────────────────────────── */
const DAY_NAMES = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

const DEFAULT_DAY = { enabled: true, start: '09:00', end: '18:00' };

const QUICK_FILL_PRESETS = {
  standard: {
    label: 'Standard (Mon-Fri)',
    days: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
    start: '09:00',
    end: '18:00',
  },
  weekend: {
    label: 'Weekend (Sat-Sun)',
    days: ['saturday', 'sunday'],
    start: '10:00',
    end: '20:00',
  },
  full: {
    label: '7/7 (Full week)',
    days: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'],
    start: '09:00',
    end: '19:00',
  },
};

/**
 * Check if a moment day falls within any blackout range (inclusive).
 */
function isDayBlocked(momentDay, blackoutList) {
  if (!blackoutList || blackoutList.length === 0) return false;
  return blackoutList.some((b) =>
    momentDay.isBetween(moment(b.start_date), moment(b.end_date), 'day', '[]'),
  );
}

/* ── BlackoutDatesManager sub-component ──────────────────────── */
function BlackoutDatesManager({ productId, isMobile }) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [focusedInput, setFocusedInput] = useState('startDate');
  const [confirmOpen, setConfirmOpen] = useState(false);

  const { data: blackouts = [], isLoading } = useQuery({
    queryKey: ['vendor-blackouts', productId],
    queryFn: () => getBlackouts(productId),
    enabled: !!productId,
  });

  const addMutation = useMutation({
    mutationFn: (data) =>
      addBlackout({
        product_id: productId,
        start_date: data.start,
        end_date: data.end,
        reason: 'Manually blocked by vendor',
      }),
    onSuccess: () => {
      queryClient.invalidateQueries(['vendor-blackouts', productId]);
      setDialogOpen(false);
      setConfirmOpen(false);
      setStartDate(null);
      setEndDate(null);
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id) => deleteBlackout(id),
    onSuccess: () => {
      queryClient.invalidateQueries(['vendor-blackouts', productId]);
    },
  });

  const handleBlock = () => {
    addMutation.mutate({
      start: startDate.format('YYYY-MM-DD'),
      end: endDate.format('YYYY-MM-DD'),
    });
  };

  if (!productId) return null;

  return (
    <Box sx={{ mt: 3, mb: 4 }}>
      {/* Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
        <Box>
          <Typography variant="h6" sx={{ display: 'flex', alignItems: 'center' }}>
            <EventBusyRoundedIcon sx={{ mr: 1, color: 'error.main' }} />
            {t('dateBlocker.title')}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {t('dateBlocker.description')}
          </Typography>
        </Box>
        <Button
          variant="outlined"
          color="error"
          startIcon={<EventBusyRoundedIcon />}
          onClick={() => setDialogOpen(true)}
        >
          {t('dateBlocker.addButton')}
        </Button>
      </Box>

      {/* Blackout list */}
      {blackouts.length > 0 ? (
        <Paper variant="outlined" sx={{ bgcolor: 'background.paper', borderRadius: 1 }}>
          <List dense>
            {blackouts.map((item) => (
              <ListItem
                key={item.id}
                sx={{ borderBottom: '1px solid #eee' }}
                secondaryAction={
                  <IconButton edge="end" onClick={() => deleteMutation.mutate(item.id)}>
                    <DeleteRoundedIcon color="action" />
                  </IconButton>
                }
              >
                <ListItemText
                  primary={
                    <Typography variant="subtitle2" color="error.main">
                      {moment(item.start_date).format('LL')} – {moment(item.end_date).format('LL')}
                    </Typography>
                  }
                  secondary={item.reason}
                />
              </ListItem>
            ))}
          </List>
        </Paper>
      ) : (
        <Alert severity="info" sx={{ bgcolor: '#f8f9fa' }}>
          {t('dateBlocker.noDates')}
        </Alert>
      )}

      {/* Date picker dialog */}
      <Dialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        maxWidth="md"
        fullWidth={!isMobile}
        fullScreen={isMobile}
      >
        <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between' }}>
          {t('dateBlocker.modalTitle')}
          {isMobile && (
            <Button onClick={() => setDialogOpen(false)}>
              {t('common.close')}
            </Button>
          )}
        </DialogTitle>
        <DialogContent dividers>
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 2 }}>
            <div style={{ height: isMobile ? '100%' : '350px' }}>
              <DayPickerRangeController
                startDate={startDate}
                endDate={endDate}
                onDatesChange={({ startDate: s, endDate: e }) => {
                  setStartDate(s);
                  setEndDate(e);
                }}
                focusedInput={focusedInput}
                onFocusChange={(focused) => setFocusedInput(focused || 'startDate')}
                initialVisibleMonth={() => moment()}
                numberOfMonths={isMobile ? 12 : 2}
                orientation={isMobile ? 'verticalScrollable' : 'horizontal'}
                isOutsideRange={(day) => day.isBefore(moment(), 'day')}
                isDayBlocked={(day) => isDayBlocked(day, blackouts)}
                hideKeyboardShortcutsPanel
                noBorder
              />
            </div>
          </Box>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button color="inherit" onClick={() => setDialogOpen(false)}>
            {t('common.cancel')}
          </Button>
          <Button
            variant="contained"
            color="error"
            startIcon={<EventBusyRoundedIcon />}
            disabled={!startDate || !endDate}
            onClick={() => setConfirmOpen(true)}
          >
            {t('dateBlocker.blockButton')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Confirmation dialog */}
      <Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)}>
        <DialogTitle>{t('dateBlocker.confirmTitle')}</DialogTitle>
        <DialogContent>
          <Typography>
            {t('dateBlocker.confirmMessage')}
          </Typography>
          <Box
            sx={{
              mt: 2,
              p: 2,
              bgcolor: '#ffebee',
              borderRadius: 1,
              textAlign: 'center',
              border: '1px dashed #ef5350',
            }}
          >
            <Typography variant="h6" color="error.main" fontWeight="bold">
              {startDate?.format('LL')} – {endDate?.format('LL')}
            </Typography>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmOpen(false)}>{t('common.cancel')}</Button>
          <Button color="error" variant="contained" onClick={handleBlock}>
            {t('common.confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

/* ── Main Component ──────────────────────────────────────────── */

/**
 * Step 3 – Availability configuration.
 *
 * Weekly schedule with per-day toggle and time pickers, quick-fill presets,
 * booking constraints, and blackout-date management.
 */
export default function Step3Availability({
  wizardData,
  updateStepData,
  settings,
  onNext,
  onBack,
  isMobile,
  productId,
}) {
  const { t, i18n } = useTranslation();
  const stepData = wizardData.step_3 || {};
  const offerType = wizardData.step_1?.offer_type || 'day';
  const category = wizardData.step_2?.category;

  /* Sync moment locale with i18n language for consistent day acronyms in react-dates */
  useEffect(() => {
    const lang = (i18n.language || 'en').split(/[-_]/)[0];
    moment.locale(lang);
  }, [i18n.language]);

  /* Category-based default times */
  const categoryDefaults =
    category && ['hotel', 'apartment', 'camping', 'house', 'room'].includes(category)
      ? { start: '15:00', end: '11:00' }
      : { start: '09:00', end: '18:00' };

  /* ── State ─────────────────────────────────────────────────── */
  const [touched, setTouched] = useState({});
  const markTouched = (field) => setTouched((prev) => ({ ...prev, [field]: true }));

  const initSchedule = () => {
    const existing = stepData.availability_schedule || {};
    const existingDays = stepData.recurring_days || DAY_NAMES.slice(0, 5);

    if (Object.keys(existing).length === 0 && Array.isArray(existingDays)) {
      const result = {};
      DAY_NAMES.forEach((day) => {
        result[day] = {
          enabled: existingDays.includes(day),
          start: stepData.start_time || categoryDefaults.start,
          end: stepData.end_time || categoryDefaults.end,
        };
      });
      return result;
    }

    const merged = { ...existing };
    DAY_NAMES.forEach((day) => {
      if (!merged[day]) {
        merged[day] = {
          ...DEFAULT_DAY,
          enabled: false,
          start: categoryDefaults.start,
          end: categoryDefaults.end,
        };
      }
    });
    return merged;
  };

  const [schedule, setSchedule] = useState(initSchedule);

  /* Merge constraint defaults from settings */
  const constraints = {
    min_duration: settings?.booking?.default_min_stay_days || 1,
    max_duration: settings?.booking?.default_max_stay_days || 30,
    min_booking_window: settings?.booking?.min_booking_window_hours || 24,
    max_booking_window: settings?.booking?.max_booking_window_days || 365,
    buffer_before: settings?.booking?.buffer_before_hours || 0,
    buffer_after: settings?.booking?.buffer_after_hours || 0,
    ...stepData,
  };

  /* Sync schedule changes → parent */
  useEffect(() => {
    updateStepData('step_3', {
      ...constraints,
      availability_schedule: schedule,
      recurring_days: DAY_NAMES.filter((d) => schedule[d].enabled),
      start_time: schedule.monday?.start || categoryDefaults.start,
      end_time: schedule.monday?.end || categoryDefaults.end,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [schedule]);

  /* ── Callbacks ─────────────────────────────────────────────── */
  const handleConstraintChange = useCallback(
    (field) => (e) => {
      const val = e.target.type === 'number' ? parseInt(e.target.value, 10) || 0 : e.target.value;
      updateStepData('step_3', { ...constraints, [field]: val });
    },
    [constraints, updateStepData],
  );

  const handleDayToggle = (day) => (e) => {
    setSchedule((prev) => ({
      ...prev,
      [day]: { ...prev[day], enabled: e.target.checked },
    }));
  };

  const handleTimeChange = (day, field) => (e) => {
    setSchedule((prev) => ({
      ...prev,
      [day]: { ...prev[day], [field]: e.target.value },
    }));
  };

  const copyToAll = (sourceDay) => {
    const src = schedule[sourceDay];
    setSchedule((prev) => {
      const updated = { ...prev };
      DAY_NAMES.forEach((d) => {
        if (d !== sourceDay) {
          updated[d] = { ...updated[d], start: src.start, end: src.end, enabled: true };
        }
      });
      return updated;
    });
  };

  const applyPreset = (presetKey) => {
    const preset = QUICK_FILL_PRESETS[presetKey];
    if (!preset) return;
    setSchedule((prev) => {
      const updated = { ...prev };
      DAY_NAMES.forEach((d) => {
        const inPreset = preset.days.includes(d);
        updated[d] = {
          ...updated[d],
          enabled: inPreset,
          start: inPreset ? preset.start : updated[d].start,
          end: inPreset ? preset.end : updated[d].end,
        };
      });
      return updated;
    });
  };

  const validateAndNext = () => {
    if (DAY_NAMES.filter((d) => schedule[d].enabled).length === 0) {
      alert(t('step3.minOneDayRequired'));
      return;
    }
    onNext();
  };

  /* ── Render ────────────────────────────────────────────────── */
  return (
    <Box sx={{ py: { xs: 2, md: 4 } }}>
      <Typography variant="h5" component="h2" fontWeight="bold" textAlign="center" sx={{ mb: 4 }}>
        {t('step3.title')}
      </Typography>

      <Box sx={{ maxWidth: 800, mx: 'auto' }}>
        {/* ═══ CARD 1: Weekly Schedule ═══ */}
        <Card sx={{ mb: 4, borderRadius: 2, overflow: 'visible' }}>
          <CardContent sx={{ p: 4 }}>
            {/* Header */}
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
              <AccessTimeRoundedIcon sx={{ color: 'primary.main', mr: 2, fontSize: 28 }} />
              <Typography variant="h6" fontWeight="bold">
                {t('step3.recurringDays')}
              </Typography>
            </Box>

            {/* Quick-fill presets */}
            <Box sx={{ mb: 3, display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              <Typography
                variant="body2"
                color="text.secondary"
                sx={{ mr: 1, alignSelf: 'center' }}
              >
                {t('step3.quickFill')}
              </Typography>
              {Object.entries(QUICK_FILL_PRESETS).map(([key, preset]) => (
                <Chip
                  key={key}
                  label={t(`step3.quickPresets.${key}`)}
                  onClick={() => applyPreset(key)}
                  variant="outlined"
                  size="small"
                  clickable
                  color="primary"
                />
              ))}
            </Box>

            <Divider sx={{ mb: 3 }} />

            {/* Day rows */}
            {DAY_NAMES.map((dayName, index) => {
              const day = schedule[dayName];
              return (
                <Box
                  key={dayName}
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    mb: 2,
                    pb: 2,
                    borderBottom: index < 6 ? '1px dashed #eee' : 'none',
                    flexWrap: isMobile ? 'wrap' : 'nowrap',
                  }}
                >
                  {/* Day toggle */}
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      width: isMobile ? '100%' : 200,
                      mb: isMobile ? 2 : 0,
                    }}
                  >
                    <Switch
                      checked={day.enabled}
                      onChange={handleDayToggle(dayName)}
                      color="primary"
                    />
                    <Typography
                      sx={{
                        fontWeight: day.enabled ? 600 : 400,
                        color: day.enabled ? 'text.primary' : 'text.disabled',
                        ml: 1,
                        textTransform: 'capitalize',
                      }}
                    >
                      {t(`step3.${dayName}`)}
                    </Typography>
                  </Box>

                  {/* Time pickers or "Closed" */}
                  {day.enabled ? (
                    <Box sx={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                      <TextField
                        type="time"
                        size="small"
                        value={day.start}
                        onChange={handleTimeChange(dayName, 'start')}
                        onBlur={() => markTouched(`${dayName}_start`)}
                        InputLabelProps={{ shrink: true }}
                        sx={{ width: 130 }}
                        error={touched[`${dayName}_start`] && !day.start}
                      />
                      <Typography sx={{ mx: 2, color: 'text.secondary' }}>—</Typography>
                      <TextField
                        type="time"
                        size="small"
                        value={day.end}
                        onChange={handleTimeChange(dayName, 'end')}
                        onBlur={() => markTouched(`${dayName}_end`)}
                        InputLabelProps={{ shrink: true }}
                        sx={{ width: 130 }}
                        error={touched[`${dayName}_end`] && !day.end}
                      />
                      <Tooltip title={t('step3.copyToAll')}>
                        <IconButton
                          size="small"
                          sx={{ ml: 2 }}
                          color="default"
                          onClick={() => copyToAll(dayName)}
                        >
                          <ContentCopyRoundedIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    </Box>
                  ) : (
                    <Typography color="text.disabled" fontStyle="italic" sx={{ ml: 2 }}>
                      {t('step3.closed')}
                    </Typography>
                  )}
                </Box>
              );
            })}
          </CardContent>
        </Card>

        {/* ═══ CARD 2: Booking Constraints ═══ */}
        <Card sx={{ mb: 4, borderRadius: 2 }}>
          <CardContent sx={{ p: 4 }}>
            <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
              <TuneRoundedIcon sx={{ color: 'secondary.main', mr: 2, fontSize: 28 }} />
              <Typography variant="h6" fontWeight="bold">
                {t('step3.constraints')}
              </Typography>
            </Box>

            <Grid container spacing={4}>
              {/* Duration (day-type only) */}
              {offerType === 'day' && (
                <Grid item xs={12}>
                  <Typography
                    variant="subtitle2"
                    color="text.secondary"
                    gutterBottom
                    sx={{ display: 'flex', alignItems: 'center' }}
                  >
                    <NightsStayRoundedIcon sx={{ fontSize: 18, mr: 1 }} />
                    {t('step3.minDuration')} / {t('step3.maxDuration')}
                  </Typography>
                  <Box sx={{ display: 'flex', gap: 2 }}>
                    <TextField
                      label={t('step3.minDuration')}
                      type="number"
                      value={constraints.min_duration}
                      onChange={handleConstraintChange('min_duration')}
                      fullWidth
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">{t('step3.days')}</InputAdornment>
                        ),
                      }}
                    />
                    <TextField
                      label={t('step3.maxDuration')}
                      type="number"
                      value={constraints.max_duration}
                      onChange={handleConstraintChange('max_duration')}
                      fullWidth
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">{t('step3.days')}</InputAdornment>
                        ),
                      }}
                    />
                  </Box>
                </Grid>
              )}

              {/* Min booking window */}
              <Grid item xs={12} md={6}>
                <Typography
                  variant="subtitle2"
                  color="text.secondary"
                  gutterBottom
                  sx={{ display: 'flex', alignItems: 'center' }}
                >
                  <HourglassEmptyRoundedIcon sx={{ fontSize: 18, mr: 1 }} />
                  {t('step3.minBookingWindow')}
                </Typography>
                <TextField
                  fullWidth
                  type="number"
                  value={constraints.min_booking_window}
                  onChange={handleConstraintChange('min_booking_window')}
                  placeholder="24"
                  InputProps={{ endAdornment: <InputAdornment position="end">h</InputAdornment> }}
                  helperText={t('step3.minBookingWindowHelp')}
                />
              </Grid>

              {/* Max booking window */}
              <Grid item xs={12} md={6}>
                <Typography
                  variant="subtitle2"
                  color="text.secondary"
                  gutterBottom
                  sx={{ display: 'flex', alignItems: 'center' }}
                >
                  <AccessTimeRoundedIcon sx={{ fontSize: 18, mr: 1 }} />
                  {t('step3.maxBookingWindow')}
                </Typography>
                <TextField
                  fullWidth
                  type="number"
                  value={constraints.max_booking_window}
                  onChange={handleConstraintChange('max_booking_window')}
                  placeholder="365"
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">{t('step3.days')}</InputAdornment>
                    ),
                  }}
                />
              </Grid>

              <Grid item xs={12}>
                <Divider />
              </Grid>

              {/* Buffer times */}
              <Grid item xs={12}>
                <Typography
                  variant="subtitle2"
                  color="text.secondary"
                  gutterBottom
                  sx={{ display: 'flex', alignItems: 'center' }}
                >
                  <SwapHorizRoundedIcon sx={{ fontSize: 18, mr: 1 }} />
                  BUFFER ({t('step3.bufferBefore')} / {t('step3.bufferAfter')})
                </Typography>
                <Box sx={{ display: 'flex', gap: 2 }}>
                  <TextField
                    label={t('step3.bufferBeforeLabel')}
                    type="number"
                    value={constraints.buffer_before}
                    onChange={handleConstraintChange('buffer_before')}
                    fullWidth
                    InputProps={{
                      endAdornment: <InputAdornment position="end">h</InputAdornment>,
                    }}
                  />
                  <TextField
                    label={t('step3.bufferAfterLabel')}
                    type="number"
                    value={constraints.buffer_after}
                    onChange={handleConstraintChange('buffer_after')}
                    fullWidth
                    InputProps={{
                      endAdornment: <InputAdornment position="end">h</InputAdornment>,
                    }}
                  />
                </Box>
                <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                  {t('step3.bufferDescription')}
                </Typography>
              </Grid>
            </Grid>
          </CardContent>
        </Card>

        {/* ═══ Blackout Dates Manager ═══ */}
        <BlackoutDatesManager productId={productId} isMobile={isMobile} />
      </Box>

      {/* ═══ Navigation ═══ */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          mt: 4,
          pt: 3,
          borderTop: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Button variant="outlined" onClick={onBack} startIcon={<NavigateBeforeRoundedIcon />}>
          {t('wizard.buttons.previous')}
        </Button>
        <Button variant="contained" onClick={validateAndNext} endIcon={<NavigateNextRoundedIcon />}>
          {t('wizard.buttons.next')}
        </Button>
      </Box>
    </Box>
  );
}
