import React, { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Alert from '@mui/material/Alert';
import Grid from '@mui/material/Grid';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction';
import Divider from '@mui/material/Divider';
import Chip from '@mui/material/Chip';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import FormControl from '@mui/material/FormControl';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import Checkbox from '@mui/material/Checkbox';

import CheckCircleRoundedIcon from '@mui/icons-material/CheckCircleRounded';
import CategoryRoundedIcon from '@mui/icons-material/CategoryRounded';
import Inventory2RoundedIcon from '@mui/icons-material/Inventory2Rounded';
import MonetizationOnRoundedIcon from '@mui/icons-material/MonetizationOnRounded';
import CalendarMonthRoundedIcon from '@mui/icons-material/CalendarMonthRounded';
import PaymentRoundedIcon from '@mui/icons-material/PaymentRounded';
import PhotoCameraRoundedIcon from '@mui/icons-material/PhotoCameraRounded';
import NavigateBeforeRoundedIcon from '@mui/icons-material/NavigateBeforeRounded';
import PublishRoundedIcon from '@mui/icons-material/PublishRounded';

const CANCELLATION_POLICIES = ['flexible', 'moderate', 'strict'];

/**
 * Step 7 – Publish.
 *
 * Summary checklist of all steps, cancellation policy selector,
 * terms acceptance checkbox, and the publish button.
 */
export default function Step7Publish({
  wizardData,
  updateStepData,
  settings,
  onBack,
  onPublish,
  isPublishing,
  isMobile,
}) {
  const { t } = useTranslation();
  const stepData = wizardData.step_7 || {};

  const [termsAccepted, setTermsAccepted] = useState(stepData.terms_accepted || false);
  const [error, setError] = useState(null);

  const currency = settings?.currency_symbol || '';
  const step1 = wizardData.step_1 || {};
  const step2 = wizardData.step_2 || {};
  const step3 = wizardData.step_3 || {};
  const step4 = wizardData.step_4 || {};
  const step5 = wizardData.step_5 || {};
  const step6 = wizardData.step_6 || {};

  const handlePolicyChange = useCallback(
    (e) => {
      updateStepData('step_7', { ...stepData, cancellation_policy: e.target.value });
    },
    [stepData, updateStepData],
  );

  const handlePublish = useCallback(() => {
    if (!termsAccepted) {
      setError(t('step7.termsError'));
      return;
    }
    if (!stepData.cancellation_policy) {
      setError(t('validation.required'));
      return;
    }
    updateStepData('step_7', { ...stepData, terms_accepted: termsAccepted });
    onPublish();
  }, [termsAccepted, stepData, updateStepData, onPublish, t]);

  const offerTypeLabel = () => {
    switch (step1.offer_type) {
      case 'day': return t('step1.day.title');
      case 'slot': return t('step1.slot.title');
      case 'service': return t('step1.service.title');
      default: return '-';
    }
  };

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

      {error && (
        <Alert severity="error" onClose={() => setError(null)} sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3} sx={{ maxWidth: 900, mx: 'auto' }}>
        {/* ── Summary checklist ──────────────────────────────── */}
        <Grid item xs={12} md={7}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step7.summary')}</Typography>
              <List disablePadding>
                {/* Offer type */}
                <ListItem>
                  <ListItemIcon><CategoryRoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText primary={t('step7.offerType')} secondary={offerTypeLabel()} />
                  <ListItemSecondaryAction><CheckCircleRoundedIcon color="success" /></ListItemSecondaryAction>
                </ListItem>
                <Divider />

                {/* Product */}
                <ListItem>
                  <ListItemIcon><Inventory2RoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText
                    primary={t('step7.product')}
                    secondary={step2.product_name || (step2.selected_product_id ? `ID: ${step2.selected_product_id}` : '-')}
                  />
                  <ListItemSecondaryAction><CheckCircleRoundedIcon color="success" /></ListItemSecondaryAction>
                </ListItem>
                <Divider />

                {/* Pricing */}
                <ListItem>
                  <ListItemIcon><MonetizationOnRoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText
                    primary={t('step7.pricing')}
                    secondary={
                      step4.base_price
                        ? `${step4.base_price} ${currency}/${step1.offer_type === 'day' ? t('step4.perDay') : t('step4.perSlot')}`
                        : '-'
                    }
                  />
                  {step4.rules?.length > 0 && (
                    <Chip label={`${step4.rules.length} ${t('step4.priceRules')}`} size="small" />
                  )}
                </ListItem>
                <Divider />

                {/* Availability */}
                <ListItem>
                  <ListItemIcon><CalendarMonthRoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText
                    primary={t('step7.availability')}
                    secondary={
                      step3.recurring_days?.length > 0
                        ? `${step3.recurring_days.length} ${t('step3.recurringDays').toLowerCase()}`
                        : '-'
                    }
                  />
                  <ListItemSecondaryAction><CheckCircleRoundedIcon color="success" /></ListItemSecondaryAction>
                </ListItem>
                <Divider />

                {/* Payment */}
                <ListItem>
                  <ListItemIcon><PaymentRoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText
                    primary={t('step7.payment')}
                    secondary={
                      [
                        step5.deposit_enabled && t('step5.deposit.title'),
                        step5.security_enabled && t('step5.security.title'),
                        step5.balance_enabled && t('step5.balance.title'),
                      ]
                        .filter(Boolean)
                        .join(', ') || '-'
                    }
                  />
                  <ListItemSecondaryAction><CheckCircleRoundedIcon color="success" /></ListItemSecondaryAction>
                </ListItem>
                <Divider />

                {/* Photos */}
                <ListItem>
                  <ListItemIcon><PhotoCameraRoundedIcon color="primary" /></ListItemIcon>
                  <ListItemText primary={t('step6.title')} secondary={`${step6.images?.length || 0} ${t('step6.title').toLowerCase()}`} />
                  {step6.images?.length > 0 ? (
                    <ListItemSecondaryAction><CheckCircleRoundedIcon color="success" /></ListItemSecondaryAction>
                  ) : (
                    <Chip label={t('common.optional')} size="small" />
                  )}
                </ListItem>
              </List>
            </CardContent>
          </Card>
        </Grid>

        {/* ── Right column: policy + terms ───────────────────── */}
        <Grid item xs={12} md={5}>
          {/* Cancellation policy */}
          <Card sx={{ mb: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step7.cancellation.title')}</Typography>
              <FormControl component="fieldset" fullWidth>
                <RadioGroup value={stepData.cancellation_policy || 'moderate'} onChange={handlePolicyChange}>
                  {CANCELLATION_POLICIES.map((policy) => (
                    <Box
                      key={policy}
                      sx={{
                        mb: 1,
                        p: 2,
                        border: '1px solid',
                        borderColor: stepData.cancellation_policy === policy ? 'primary.main' : 'divider',
                        borderRadius: 1,
                        backgroundColor: stepData.cancellation_policy === policy ? 'primary.light' : 'transparent',
                        cursor: 'pointer',
                      }}
                      onClick={() => handlePolicyChange({ target: { value: policy } })}
                    >
                      <FormControlLabel
                        value={policy}
                        control={<Radio />}
                        label={
                          <Box>
                            <Typography variant="subtitle2">
                              {t(`step7.cancellation.${policy}.name`)}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {t(`step7.cancellation.${policy}.description`)}
                            </Typography>
                          </Box>
                        }
                        sx={{ m: 0, width: '100%' }}
                      />
                    </Box>
                  ))}
                </RadioGroup>
              </FormControl>
            </CardContent>
          </Card>

          {/* Terms */}
          <Card>
            <CardContent>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={termsAccepted}
                    onChange={(e) => setTermsAccepted(e.target.checked)}
                  />
                }
                label={t('step7.terms')}
              />
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* ═══ Navigation ═══ */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          mt: 4,
          pt: 3,
          borderTop: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Button
          variant="outlined"
          onClick={onBack}
          startIcon={<NavigateBeforeRoundedIcon />}
          disabled={isPublishing}
        >
          {t('wizard.buttons.previous')}
        </Button>
        <Button
          variant="contained"
          color="success"
          onClick={handlePublish}
          disabled={isPublishing || !termsAccepted}
          startIcon={isPublishing ? <CircularProgress size={20} color="inherit" /> : <PublishRoundedIcon />}
          size="large"
        >
          {t(isPublishing ? 'common.loading' : 'wizard.buttons.publish')}
        </Button>
      </Box>
    </Box>
  );
}
