import React, { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import Grid from '@mui/material/Grid';
import Card from '@mui/material/Card';
import CardActionArea from '@mui/material/CardActionArea';
import CardMedia from '@mui/material/CardMedia';
import CardContent from '@mui/material/CardContent';
import Chip from '@mui/material/Chip';
import Button from '@mui/material/Button';
import SearchRoundedIcon from '@mui/icons-material/SearchRounded';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded';
import AddShoppingCartRoundedIcon from '@mui/icons-material/AddShoppingCartRounded';
import Inventory2RoundedIcon from '@mui/icons-material/Inventory2Rounded';
import CheckRoundedIcon from '@mui/icons-material/CheckRounded';

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

/**
 * Step 2 – Product selection.
 *
 * Fetches the vendor's WooCommerce products and lets them pick one
 * to attach the rental offer to.
 */
export default function Step2ProductSelect({
  wizardData,
  updateStepData,
  productId,
  setProductId,
  onNext,
  onBack,
  isMobile,
}) {
  const { t } = useTranslation();
  const stepData = wizardData.step_2 || {};
  const [search, setSearch] = useState('');

  /* ── Products query ────────────────────────────────────────── */
  const {
    data: products = [],
    isLoading,
    error,
  } = useQuery({
    queryKey: ['vendor-products', search],
    queryFn: () => getProducts(search),
    staleTime: 1000 * 60 * 5,
  });

  /* ── Client-side filter (also matches SKU) ─────────────────── */
  const filtered = useMemo(() => {
    if (!search.trim()) return products;
    const q = search.toLowerCase();
    return products.filter(
      (p) => p.name.toLowerCase().includes(q) || p.sku?.toLowerCase().includes(q),
    );
  }, [products, search]);

  /* ── Select handler ────────────────────────────────────────── */
  const handleSelect = useCallback(
    (product) => {
      setProductId(product.id);
      updateStepData('step_2', {
        ...stepData,
        selected_product_id: product.id,
        product_name: product.name,
        product_image: product.image,
        product_price: product.price,
      });
    },
    [stepData, updateStepData, setProductId],
  );

  const handleNext = () => {
    if (productId) onNext();
  };

  /* ── Loading state ─────────────────────────────────────────── */
  if (isLoading) {
    return (
      <Box sx={{ py: 8, textAlign: 'center' }}>
        <CircularProgress size={48} />
        <Typography variant="body1" color="text.secondary" sx={{ mt: 2 }}>
          {t('step2.loading')}
        </Typography>
      </Box>
    );
  }

  /* ── Error state ───────────────────────────────────────────── */
  if (error) {
    return (
      <Box sx={{ py: 4 }}>
        <Alert severity="error">
          {t('step2.loadError')}
        </Alert>
      </Box>
    );
  }

  /* ── Empty state ───────────────────────────────────────────── */
  if (products.length === 0) {
    return (
      <Box sx={{ py: { xs: 4, md: 8 }, textAlign: 'center', maxWidth: 500, mx: 'auto' }}>
        <Box
          sx={{
            width: 120,
            height: 120,
            borderRadius: '50%',
            backgroundColor: '#f1f5f9',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            mx: 'auto',
            mb: 3,
          }}
        >
          <Inventory2RoundedIcon sx={{ fontSize: 56, color: '#94a3b8' }} />
        </Box>
        <Typography variant="h5" fontWeight="bold" gutterBottom>
          {t('step2.noProducts')}
        </Typography>
        <Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
          {t('step2.noProductsDesc')}
        </Typography>
        <Button
          variant="contained"
          size="large"
          startIcon={<AddShoppingCartRoundedIcon />}
          href={window.wahrbWizardConfig?.productsUrl || '/dashboard/products/?action=new'}
          sx={{ px: 4 }}
        >
          {t('step2.createFirstProduct')}
        </Button>
        <Box sx={{ mt: 4, pt: 3, borderTop: '1px solid', borderColor: 'divider' }}>
          <Button variant="text" onClick={onBack} startIcon={<ArrowBackRoundedIcon />}>
            {t('common.back')}
          </Button>
        </Box>
      </Box>
    );
  }

  /* ── Normal view (products available) ──────────────────────── */
  return (
    <Box sx={{ py: { xs: 2, md: 4 } }}>
      <Typography variant="h5" component="h2" fontWeight="bold" textAlign="center" sx={{ mb: 1 }}>
        {t('step2.title')}
      </Typography>
      <Typography variant="body1" color="text.secondary" textAlign="center" sx={{ mb: 4 }}>
        {t('step2.subtitle')}
      </Typography>

      {/* Search bar */}
      <Box sx={{ maxWidth: 500, mx: 'auto', mb: 4 }}>
        <TextField
          fullWidth
          placeholder={t('step2.search')}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchRoundedIcon color="action" />
              </InputAdornment>
            ),
          }}
          sx={{ '& .MuiOutlinedInput-root': { borderRadius: 3, backgroundColor: '#f8fafc' } }}
        />
      </Box>

      {/* Product grid */}
      <Grid container spacing={3} sx={{ maxWidth: 900, mx: 'auto' }}>
        {filtered.map((product) => {
          const isSelected = productId === product.id;
          return (
            <Grid item xs={12} sm={6} md={4} key={product.id}>
              <Card
                sx={{
                  height: '100%',
                  border: '3px solid',
                  borderColor: isSelected ? 'primary.main' : 'transparent',
                  boxShadow: isSelected ? 4 : 1,
                  transition: 'all 0.2s ease',
                  position: 'relative',
                  '&:hover': { boxShadow: 4, transform: 'translateY(-2px)' },
                }}
              >
                <CardActionArea onClick={() => handleSelect(product)}>
                  <CardMedia
                    component="img"
                    height={160}
                    image={
                      product.image ||
                      `${window.wahrbWizardConfig?.pluginUrl || ''}/assets/images/no-image.png`
                    }
                    alt={product.name}
                    sx={{ objectFit: 'cover' }}
                  />

                  {isSelected && (
                    <Box
                      sx={{
                        position: 'absolute',
                        top: 12,
                        right: 12,
                        backgroundColor: 'primary.main',
                        color: 'white',
                        borderRadius: '50%',
                        width: 32,
                        height: 32,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}
                    >
                      <CheckRoundedIcon fontSize="small" />
                    </Box>
                  )}

                  <CardContent>
                    <Typography variant="subtitle1" fontWeight="600" noWrap>
                      {product.name}
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 1 }}>
                      {product.price && (
                        <Chip
                          label={`${product.price} ${window.wahrbWizardConfig?.currencySymbol || ''}`}
                          size="small"
                          color="primary"
                          variant="outlined"
                        />
                      )}
                      {product.stock_status === 'instock' && (
                        <Chip label={t('step2.inStock')} size="small" color="success" variant="outlined" />
                      )}
                    </Box>
                  </CardContent>
                </CardActionArea>
              </Card>
            </Grid>
          );
        })}
      </Grid>

      {/* No results message */}
      {filtered.length === 0 && search && (
        <Box sx={{ py: 4, textAlign: 'center' }}>
          <Typography color="text.secondary">
            {t('step2.noResults', { search })}
          </Typography>
        </Box>
      )}

      {/* Navigation */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          mt: 4,
          pt: 3,
          borderTop: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Button variant="outlined" onClick={onBack} startIcon={<ArrowBackRoundedIcon />}>
          {t('common.back')}
        </Button>
        <Button
          variant="contained"
          onClick={handleNext}
          disabled={!productId}
          endIcon={<ArrowForwardRoundedIcon />}
        >
          {t('common.next')}
        </Button>
      </Box>
    </Box>
  );
}
