import { useNavigate } from 'react-router-dom';
import Box from '@mui/material/Box';
import { ComparisonPage } from '../../../../components/pages/ComparisonPage';
import { Typography } from '../../../../components/atoms/Typography';
import { Button } from '../../../../components/atoms/Button';
import { useComparisonBasket } from '../../../shared/state/useComparisonBasket';
import { resolveComparisonPackage } from '../../../shared/fixtures/packages';
import { demoNav } from '../DemoNav';

export function ComparisonRoute() {
  const navigate = useNavigate();
  const packageKeys = useComparisonBasket((s) => s.packageKeys);
  const remove = useComparisonBasket((s) => s.remove);

  const packages = packageKeys
    .map((key) => {
      const resolved = resolveComparisonPackage(key);
      return resolved ? { key, pkg: resolved } : null;
    })
    .filter(
      (x): x is { key: string; pkg: NonNullable<ReturnType<typeof resolveComparisonPackage>> } =>
        x !== null,
    );

  if (packages.length === 0) {
    return (
      <Box sx={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
        {demoNav}
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 2,
            p: 4,
            textAlign: 'center',
          }}
        >
          <Typography variant="h4">Nothing to compare yet</Typography>
          <Typography variant="body1" color="text.secondary">
            Pick a provider, choose a package, then tap Compare.
          </Typography>
          <Button onClick={() => navigate('/')}>Browse providers</Button>
        </Box>
      </Box>
    );
  }

  return (
    <ComparisonPage
      packages={packages.map((p) => p.pkg)}
      onArrange={(id) => alert(`Arrange "${id}" — would route to next wizard step.`)}
      onRemove={(id) => {
        // ComparisonPackage.id is the bare package id; we need the basket's
        // compound key. Find it back via the parallel array.
        const entry = packages.find((p) => p.pkg.id === id);
        if (entry) remove(entry.key);
      }}
      onBack={() => navigate(-1)}
      navigation={demoNav}
    />
  );
}
