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

import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
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 Switch from '@mui/material/Switch';
import FormControlLabel from '@mui/material/FormControlLabel';
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 Divider from '@mui/material/Divider';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableRow from '@mui/material/TableRow';
import TableCell from '@mui/material/TableCell';

import NavigateBeforeRoundedIcon from '@mui/icons-material/NavigateBeforeRounded';
import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded';

/**
 * Step 5 – Payment settings.
 *
 * Deposit configuration, security deposit, balance payment,
 * and a live 3-day example summary table.
 */
export default function Step5Payment({ wizardData, updateStepData, settings, onNext, onBack, isMobile }) {
  const { t } = useTranslation();
  const stepData = wizardData.step_5 || {};
  const basePrice = wizardData.step_4?.base_price || 100;
  const currency = settings?.currency_symbol || '';

  /* ── Merged defaults ───────────────────────────────────────── */
  const config = useMemo(() => ({
    deposit_enabled: settings?.payment?.deposit_enabled ?? true,
    deposit_type: settings?.payment?.deposit_type ?? 'percent',
    deposit_value: settings?.payment?.deposit_value ?? 30,
    deposit_refundable: settings?.payment?.deposit_refundable ?? true,
    security_enabled: settings?.payment?.security_deposit_enabled ?? true,
    security_amount: 0,
    security_mode: settings?.payment?.security_mode ?? 'capture',
    balance_enabled: settings?.payment?.balance_enabled ?? true,
    balance_due_days: settings?.payment?.balance_due_days_before ?? 3,
    balance_allow_cod: settings?.payment?.balance_allow_cod ?? true,
    ...stepData,
  }), [settings, stepData]);

  const handleChange = useCallback(
    (field) => (e) => {
      const val =
        e.target.type === 'checkbox'
          ? e.target.checked
          : e.target.type === 'number'
            ? parseFloat(e.target.value) || 0
            : e.target.value;
      updateStepData('step_5', { ...config, [field]: val });
    },
    [config, updateStepData],
  );

  /* ── Summary calculations (3-day example) ──────────────────── */
  const totalExample = basePrice * 3;
  const depositAmount =
    config.deposit_type === 'percent'
      ? (totalExample * config.deposit_value) / 100
      : config.deposit_value;
  const balanceDue = config.deposit_enabled ? totalExample - depositAmount : 0;
  const securityTotal = config.security_enabled && config.security_amount > 0 ? config.security_amount : 0;
  const payNow = (config.deposit_enabled ? depositAmount : totalExample) + securityTotal;

  const handleNext = () => {
    updateStepData('step_5', config);
    onNext();
  };

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

      <Grid container spacing={3} sx={{ maxWidth: 1000, mx: 'auto' }}>
        {/* ── Deposit ────────────────────────────────────────── */}
        <Grid item xs={12} md={6}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step5.deposit.title')}</Typography>
              <FormControlLabel
                control={<Switch checked={config.deposit_enabled} onChange={handleChange('deposit_enabled')} />}
                label={t('step5.deposit.enabled')}
                sx={{ mb: 2 }}
              />
              {config.deposit_enabled && (
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <FormControl fullWidth size="small">
                      <InputLabel>{t('step5.deposit.type')}</InputLabel>
                      <Select value={config.deposit_type} onChange={handleChange('deposit_type')} label={t('step5.deposit.type')}>
                        <MenuItem value="percent">{t('step5.deposit.percent')}</MenuItem>
                        <MenuItem value="fixed">{t('step5.deposit.fixed')}</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid item xs={6}>
                    <TextField
                      label={t('step5.deposit.value')}
                      type="number"
                      value={config.deposit_value}
                      onChange={handleChange('deposit_value')}
                      fullWidth
                      size="small"
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            {config.deposit_type === 'percent' ? '%' : currency}
                          </InputAdornment>
                        ),
                      }}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <FormControlLabel
                      control={<Switch checked={config.deposit_refundable} onChange={handleChange('deposit_refundable')} size="small" />}
                      label={t('step5.deposit.refundable')}
                    />
                  </Grid>
                </Grid>
              )}
            </CardContent>
          </Card>
        </Grid>

        {/* ── Security Deposit ───────────────────────────────── */}
        <Grid item xs={12} md={6}>
          <Card sx={{ height: '100%' }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step5.security.title')}</Typography>
              <FormControlLabel
                control={<Switch checked={config.security_enabled} onChange={handleChange('security_enabled')} />}
                label={t('step5.security.enabled')}
                sx={{ mb: 2 }}
              />
              {config.security_enabled && (
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      label={t('step5.security.amount')}
                      type="number"
                      value={config.security_amount}
                      onChange={handleChange('security_amount')}
                      fullWidth
                      size="small"
                      InputProps={{ endAdornment: <InputAdornment position="end">{currency}</InputAdornment> }}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <FormControl fullWidth size="small">
                      <InputLabel>{t('step5.security.mode')}</InputLabel>
                      <Select value={config.security_mode} onChange={handleChange('security_mode')} label={t('step5.security.mode')}>
                        <MenuItem value="capture">{t('step5.security.capture')}</MenuItem>
                        <MenuItem value="authorization" disabled>{t('step5.security.authorization')}</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                </Grid>
              )}
            </CardContent>
          </Card>
        </Grid>

        {/* ── Balance ────────────────────────────────────────── */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step5.balance.title')}</Typography>
              <FormControlLabel
                control={
                  <Switch
                    checked={config.balance_enabled}
                    onChange={handleChange('balance_enabled')}
                    disabled={!config.deposit_enabled}
                  />
                }
                label={t('step5.balance.enabled')}
                sx={{ mb: 2 }}
              />
              {config.balance_enabled && config.deposit_enabled && (
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      label={t('step5.balance.dueDays')}
                      type="number"
                      value={config.balance_due_days}
                      onChange={handleChange('balance_due_days')}
                      fullWidth
                      size="small"
                      inputProps={{ min: 0 }}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <FormControlLabel
                      control={<Switch checked={config.balance_allow_cod} onChange={handleChange('balance_allow_cod')} size="small" />}
                      label={t('step5.balance.allowCod')}
                    />
                  </Grid>
                </Grid>
              )}
            </CardContent>
          </Card>
        </Grid>

        {/* ── Summary ────────────────────────────────────────── */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('step5.summary.title')}</Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                {t('step5.summary.forTotal')}: {totalExample.toFixed(2)} {currency} (3 {t('step3.days')})
              </Typography>
              <Divider sx={{ my: 2 }} />
              <Table size="small">
                <TableBody>
                  {config.deposit_enabled && (
                    <TableRow>
                      <TableCell>{t('step5.summary.payNow')}</TableCell>
                      <TableCell align="right"><strong>{depositAmount.toFixed(2)} {currency}</strong></TableCell>
                    </TableRow>
                  )}
                  {config.security_enabled && securityTotal > 0 && (
                    <TableRow>
                      <TableCell>{t('step5.summary.refundable')}</TableCell>
                      <TableCell align="right">{securityTotal.toFixed(2)} {currency}</TableCell>
                    </TableRow>
                  )}
                  {config.balance_enabled && config.deposit_enabled && (
                    <TableRow>
                      <TableCell>{t('step5.summary.payLater')}</TableCell>
                      <TableCell align="right">{balanceDue.toFixed(2)} {currency}</TableCell>
                    </TableRow>
                  )}
                  <TableRow>
                    <TableCell colSpan={2}><Divider /></TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell><strong>{t('step5.summary.payNow')}</strong></TableCell>
                    <TableCell align="right">
                      <Typography variant="h6" color="primary">{payNow.toFixed(2)} {currency}</Typography>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </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 />}>
          {t('wizard.buttons.previous')}
        </Button>
        <Button variant="contained" onClick={handleNext} endIcon={<NavigateNextRoundedIcon />}>
          {t('wizard.buttons.next')}
        </Button>
      </Box>
    </Box>
  );
}
