import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useMutation } from '@tanstack/react-query';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import IconButton from '@mui/material/IconButton';
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 FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import ButtonGroup from '@mui/material/ButtonGroup';

import MonetizationOnRoundedIcon from '@mui/icons-material/MonetizationOnRounded';
import TuneRoundedIcon from '@mui/icons-material/TuneRounded';
import TrendingUpRoundedIcon from '@mui/icons-material/TrendingUpRounded';
import TrendingDownRoundedIcon from '@mui/icons-material/TrendingDownRounded';
import EditRoundedIcon from '@mui/icons-material/EditRounded';
import DeleteRoundedIcon from '@mui/icons-material/DeleteRounded';
import RuleRoundedIcon from '@mui/icons-material/RuleRounded';
import NavigateBeforeRoundedIcon from '@mui/icons-material/NavigateBeforeRounded';
import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded';
import CalculateRoundedIcon from '@mui/icons-material/CalculateRounded';

import { getPricePreview } from '../hooks/useApi';

/**
 * Step 4 – Pricing.
 *
 * Base price + dynamic pricing rules (weekend surcharge, long-stay discount,
 * custom date-range / weekday / duration / guest rules).
 * Includes a live price preview panel.
 */
export default function Step4Pricing({ wizardData, updateStepData, settings, onNext, onBack, isMobile }) {
  const { t } = useTranslation();
  const stepData = wizardData.step_4 || {};
  const offerType = wizardData.step_1?.offer_type || 'day';

  const [editIndex, setEditIndex] = useState(-1);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [rule, setRule] = useState({});
  const [touched, setTouched] = useState({});
  const markTouched = (field) => setTouched((prev) => ({ ...prev, [field]: true }));

  const [previewDates, setPreviewDates] = useState({ start: '', end: '' });
  const currency = settings?.currency_symbol || '';

  const previewMutation = useMutation({ mutationFn: (data) => getPricePreview(data) });

  /* ── Helpers ───────────────────────────────────────────────── */
  const unitLabel = () => {
    switch (offerType) {
      case 'slot': return t('step4.perSlot');
      case 'service': return t('step4.perService');
      default: return t('step4.perDay');
    }
  };

  const handleBasePrice = useCallback(
    (e) => {
      const val = parseFloat(e.target.value) || 0;
      updateStepData('step_4', { ...stepData, base_price: val });
    },
    [stepData, updateStepData],
  );

  /* ── Smart rule templates ──────────────────────────────────── */
  const hasTemplate = (type) => {
    const rules = stepData.rules || [];
    if (type === 'weekend') {
      return rules.some((r) => r.type === 'weekday' && r.conditions?.days?.includes('saturday'));
    }
    if (type === 'longStay') {
      return rules.some((r) => r.type === 'duration' && r.conditions?.min === 7);
    }
    return false;
  };

  const toggleTemplate = (type) => {
    let rules = [...(stepData.rules || [])];

    if (hasTemplate(type)) {
      // Remove template
      if (type === 'weekend') {
        rules = rules.filter((r) => !(r.type === 'weekday' && r.conditions?.days?.includes('saturday')));
      } else if (type === 'longStay') {
        rules = rules.filter((r) => !(r.type === 'duration' && r.conditions?.min === 7));
      }
    } else {
      // Add template
      if (type === 'weekend') {
        rules.push({
          name: t('step4.templates.weekend'),
          type: 'weekday',
          modifier_type: 'percent',
          modifier_value: 10,
          conditions: { days: ['saturday', 'sunday'] },
        });
      } else if (type === 'longStay') {
        rules.push({
          name: t('step4.templates.longStay'),
          type: 'duration',
          modifier_type: 'percent',
          modifier_value: -15,
          conditions: { min: 7 },
        });
      }
    }
    updateStepData('step_4', { ...stepData, rules });
  };

  /* ── Rule CRUD ─────────────────────────────────────────────── */
  const openNew = () => {
    setEditIndex(-1);
    setDialogOpen(true);
  };

  const openEdit = (index) => {
    const r = stepData.rules[index];
    setRule({
      ...r,
      operation: (r.modifier_value || 0) < 0 ? 'decrease' : 'increase',
      modifier_value: Math.abs(r.modifier_value || 0),
    });
    setEditIndex(index);
    setDialogOpen(true);
  };

  const saveRule = () => {
    const rules = [...(stepData.rules || [])];
    const signedVal = rule.modifier_value * (rule.operation === 'decrease' ? -1 : 1);
    const newRule = { ...rule, modifier_value: signedVal };
    if (editIndex === -1) rules.push(newRule);
    else rules[editIndex] = newRule;
    updateStepData('step_4', { ...stepData, rules });
    setDialogOpen(false);
  };

  const deleteRule = useCallback(
    (index) => {
      const rules = (stepData.rules || []).filter((_, i) => i !== index);
      updateStepData('step_4', { ...stepData, rules });
    },
    [stepData, updateStepData],
  );

  /* ── Preview ───────────────────────────────────────────────── */
  const doPreview = useCallback(() => {
    if (!previewDates.start || !previewDates.end || !stepData.base_price) return;
    previewMutation.mutate({
      base_price: stepData.base_price,
      rules: stepData.rules || [],
      start_date: previewDates.start,
      end_date: previewDates.end,
      qty: 1,
    });
  }, [previewDates, stepData, previewMutation]);

  const handleNext = () => {
    if (!stepData.base_price || stepData.base_price <= 0) return;
    onNext();
  };

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

      <Grid container spacing={4} sx={{ maxWidth: 1100, mx: 'auto' }}>
        {/* Left column – base price + rules */}
        <Grid item xs={12} md={7}>
          {/* Base price */}
          <Paper elevation={0} sx={{ p: 3, mb: 3, border: '1px solid #e0e0e0', borderRadius: 2, bgcolor: '#fff' }}>
            <Box display="flex" alignItems="center" mb={2}>
              <MonetizationOnRoundedIcon color="primary" sx={{ mr: 1 }} />
              <Typography variant="h6" fontWeight="bold">{t('step4.basePrice')}</Typography>
            </Box>
            <TextField
              type="number"
              value={stepData.base_price || ''}
              onChange={handleBasePrice}
              onBlur={() => markTouched('base_price')}
              fullWidth
              placeholder="0.00"
              error={touched.base_price && (!stepData.base_price || stepData.base_price <= 0)}
              helperText={touched.base_price && (!stepData.base_price || stepData.base_price <= 0) ? t('step4.required') : ''}
              InputProps={{
                startAdornment: <InputAdornment position="start">{currency}</InputAdornment>,
                endAdornment: (
                  <InputAdornment position="end">
                    <Typography color="text.secondary" variant="body2">{unitLabel()}</Typography>
                  </InputAdornment>
                ),
                sx: { fontSize: '1.5rem', fontWeight: 'bold' },
              }}
              inputProps={{ min: 0, step: 0.01, inputMode: 'decimal' }}
            />
          </Paper>

          {/* Pricing rules */}
          <Box mb={3}>
            <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
              <Typography variant="h6" fontWeight="bold">{t('step4.priceRules')}</Typography>
            </Box>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              {t('step4.smartPricingOptions')}
            </Typography>

            {/* Template chips */}
            <Box display="flex" gap={1} mb={2} flexWrap="wrap">
              <Chip
                icon={<TuneRoundedIcon />}
                label={t('step4.templates.weekend')}
                onClick={() => toggleTemplate('weekend')}
                color={hasTemplate('weekend') ? 'primary' : 'default'}
                variant={hasTemplate('weekend') ? 'filled' : 'outlined'}
                clickable
                sx={{ borderRadius: '8px', fontWeight: hasTemplate('weekend') ? 'bold' : 'normal' }}
              />
              <Chip
                icon={<TuneRoundedIcon />}
                label={t('step4.templates.longStay')}
                onClick={() => toggleTemplate('longStay')}
                color={hasTemplate('longStay') ? 'secondary' : 'default'}
                variant={hasTemplate('longStay') ? 'filled' : 'outlined'}
                clickable
                sx={{ borderRadius: '8px', fontWeight: hasTemplate('longStay') ? 'bold' : 'normal' }}
              />
              <Chip
                icon={<TuneRoundedIcon />}
                label={t('step4.addRule')}
                onClick={openNew}
                variant="outlined"
                clickable
                sx={{ borderRadius: '8px' }}
              />
            </Box>

            {/* Rules list */}
            <Card variant="outlined">
              {(stepData.rules || []).length === 0 ? (
                <CardContent sx={{ textAlign: 'center', py: 4 }}>
                  <RuleRoundedIcon sx={{ fontSize: 40, color: 'text.disabled', mb: 1 }} />
                  <Typography color="text.secondary">{t('step4.noRules')}</Typography>
                </CardContent>
              ) : (
                <List disablePadding>
                  {(stepData.rules || []).map((r, idx) => (
                    <React.Fragment key={idx}>
                      {idx > 0 && <Divider />}
                      <ListItem
                        secondaryAction={
                          <Box>
                            <IconButton edge="end" onClick={() => openEdit(idx)} sx={{ mr: 1 }}>
                              <EditRoundedIcon />
                            </IconButton>
                            <IconButton edge="end" onClick={() => deleteRule(idx)} color="error">
                              <DeleteRoundedIcon />
                            </IconButton>
                          </Box>
                        }
                      >
                        <ListItemText
                          primary={
                            <Box display="flex" alignItems="center">
                              {r.modifier_value < 0 ? (
                                <TrendingDownRoundedIcon color="success" sx={{ mr: 1, fontSize: 18 }} />
                              ) : (
                                <TrendingUpRoundedIcon color="error" sx={{ mr: 1, fontSize: 18 }} />
                              )}
                              <Typography fontWeight="500">{r.name || t('step4.ruleSummary')}</Typography>
                            </Box>
                          }
                          secondary={
                            <Typography variant="body2" color="text.secondary">
                              {r.modifier_value > 0 ? '+' : ''}
                              {r.modifier_value}
                              {r.modifier_type === 'percent' ? '%' : currency} •{' '}
                              {r.type === 'date_range' && r.date_start && r.date_end
                                ? `${r.date_start} ➞ ${r.date_end}`
                                : t(`step4.ruleTypes.${r.type}`)}
                            </Typography>
                          }
                        />
                      </ListItem>
                    </React.Fragment>
                  ))}
                </List>
              )}
            </Card>
          </Box>
        </Grid>

        {/* Right column – price preview */}
        <Grid item xs={12} md={5}>
          <Card sx={{ position: { md: 'sticky' }, top: 20, bgcolor: '#f8fafc' }}>
            <CardContent>
              <Typography variant="h6" gutterBottom display="flex" alignItems="center">
                <CalculateRoundedIcon sx={{ mr: 1 }} />
                {t('step4.preview')}
              </Typography>
              <Typography variant="body2" color="text.secondary" paragraph>
                {t('step4.selectDates')}
              </Typography>

              <Grid container spacing={2} sx={{ mb: 3 }}>
                <Grid item xs={6}>
                  <TextField
                    label={t('common.from')}
                    type="date"
                    value={previewDates.start}
                    onChange={(e) => setPreviewDates((p) => ({ ...p, start: e.target.value }))}
                    fullWidth
                    InputLabelProps={{ shrink: true }}
                    size="small"
                    sx={{ bgcolor: 'white' }}
                  />
                </Grid>
                <Grid item xs={6}>
                  <TextField
                    label={t('common.to')}
                    type="date"
                    value={previewDates.end}
                    onChange={(e) => setPreviewDates((p) => ({ ...p, end: e.target.value }))}
                    fullWidth
                    InputLabelProps={{ shrink: true }}
                    size="small"
                    sx={{ bgcolor: 'white' }}
                  />
                </Grid>
              </Grid>

              <Button
                variant="contained"
                onClick={doPreview}
                disabled={!previewDates.start || !previewDates.end || !stepData.base_price || previewMutation.isPending}
                fullWidth
              >
                {previewMutation.isPending ? t('common.loading') : t('step4.preview')}
              </Button>

              {previewMutation.data && (
                <Box sx={{ mt: 3, p: 2, bgcolor: '#e0f2f1', borderRadius: 2, border: '1px solid #b2dfdb' }}>
                  <Box display="flex" justifyContent="space-between" mb={1}>
                    <Typography color="text.secondary">
                      {previewMutation.data.days} {t('step3.days')}
                    </Typography>
                  </Box>
                  <Typography variant="h4" fontWeight="bold" color="primary.dark">
                    {previewMutation.data.total.toFixed(2)} {currency}
                  </Typography>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* ═══ Rule editor dialog ═══ */}
      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{t(editIndex === -1 ? 'step4.addRule' : 'step4.ruleSummary')}</DialogTitle>
        <DialogContent dividers>
          <Grid container spacing={2} sx={{ mt: 0 }}>
            <Grid item xs={12}>
              <TextField
                label={t('step4.ruleName')}
                value={rule.name || ''}
                onChange={(e) => setRule({ ...rule, name: e.target.value })}
                fullWidth
                placeholder="e.g., Summer Special"
              />
            </Grid>

            <Grid item xs={12} sm={6}>
              <FormControl fullWidth>
                <InputLabel>{t('step4.ruleType')}</InputLabel>
                <Select
                  value={rule.type || 'date_range'}
                  onChange={(e) => setRule({ ...rule, type: e.target.value })}
                  label={t('step4.ruleType')}
                >
                  <MenuItem value="date_range">{t('step4.ruleTypes.date_range')}</MenuItem>
                  <MenuItem value="weekday">{t('step4.ruleTypes.weekday')}</MenuItem>
                  <MenuItem value="duration">{t('step4.ruleTypes.duration')}</MenuItem>
                  <MenuItem value="guests">{t('step4.ruleTypes.guests')}</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            {/* Date range fields */}
            {rule.type === 'date_range' && (
              <>
                <Grid item xs={6}>
                  <TextField
                    label={t('common.startDate')}
                    type="date"
                    value={rule.date_start || ''}
                    onChange={(e) => setRule({ ...rule, date_start: e.target.value })}
                    fullWidth
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                <Grid item xs={6}>
                  <TextField
                    label={t('common.endDate')}
                    type="date"
                    value={rule.date_end || ''}
                    onChange={(e) => setRule({ ...rule, date_end: e.target.value })}
                    fullWidth
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
              </>
            )}

            {rule.type === 'weekday' && (
              <Grid item xs={12}>
                <Typography variant="caption" color="text.secondary">
                  {t('step4.weekdayHelp')}
                </Typography>
              </Grid>
            )}

            {/* Modifier controls */}
            <Grid item xs={12}>
              <Divider sx={{ my: 2 }} />
              <Typography variant="subtitle2" gutterBottom sx={{ mt: 1 }}>
                {t('step4.priceImpact')}
              </Typography>
              <Grid container spacing={2} alignItems="center">
                <Grid item xs={12} sm={4}>
                  <ButtonGroup fullWidth>
                    <Button
                      variant={rule.operation === 'increase' ? 'contained' : 'outlined'}
                      color="error"
                      onClick={() => setRule({ ...rule, operation: 'increase' })}
                    >
                      <TrendingUpRoundedIcon />
                    </Button>
                    <Button
                      variant={rule.operation === 'decrease' ? 'contained' : 'outlined'}
                      color="success"
                      onClick={() => setRule({ ...rule, operation: 'decrease' })}
                    >
                      <TrendingDownRoundedIcon />
                    </Button>
                  </ButtonGroup>
                </Grid>
                <Grid item xs={8} sm={4}>
                  <TextField
                    type="number"
                    value={rule.modifier_value || 0}
                    onChange={(e) => setRule({ ...rule, modifier_value: parseFloat(e.target.value) || 0 })}
                    fullWidth
                    size="small"
                    inputProps={{ min: 0 }}
                  />
                </Grid>
                <Grid item xs={4} sm={4}>
                  <FormControl fullWidth size="small">
                    <Select
                      value={rule.modifier_type || 'percent'}
                      onChange={(e) => setRule({ ...rule, modifier_type: e.target.value })}
                    >
                      <MenuItem value="percent">%</MenuItem>
                      <MenuItem value="fixed">{currency}</MenuItem>
                    </Select>
                  </FormControl>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>{t('common.cancel')}</Button>
          <Button
            onClick={saveRule}
            variant="contained"
            disabled={rule.type === 'date_range' && (!rule.date_start || !rule.date_end)}
          >
            {t('common.save')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* ═══ 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={handleNext}
          disabled={!stepData.base_price || stepData.base_price <= 0}
          endIcon={<NavigateNextRoundedIcon />}
        >
          {t('wizard.buttons.next')}
        </Button>
      </Box>
    </Box>
  );
}
