import { Avatar, Card, Radio, Stack, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import type { TPaymentCurrency } from '@blocklet/payment-types';

const CurrencyRoot = styled('section')`
  display: grid;
  width: 100%;
  gap: 12px;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));

  .cko-payment-card {
    position: relative;
    border: 1px solid ${({ theme }) => theme.palette.primary.main};
    padding: 4px 8px;
    cursor: pointer;
    background: ${({ theme }) => theme.palette.grey[50]};
  }

  .cko-payment-card-unselect {
    border: 1px solid ${({ theme }) => theme.palette.divider};
    padding: 4px 8px;
    cursor: pointer;
    background: ${({ theme }) => theme.palette.grey[50]};
  }
`;

interface CurrencyGridProps {
  currencies: TPaymentCurrency[];
  selectedId: string | undefined;
  onSelect: (id: string) => Promise<void>;
}

export default function CurrencyGrid({ currencies, selectedId, onSelect }: CurrencyGridProps) {
  if (!currencies?.length) return null;
  return (
    <CurrencyRoot style={{ display: currencies.length > 1 ? 'grid' : 'block' }}>
      {currencies.map((cur) => {
        const selected = cur.id === selectedId;
        const methodName = (cur as any).method?.name || cur.name || '';
        return (
          <Card
            key={cur.id}
            variant="outlined"
            onClick={() => onSelect(cur.id)}
            className={selected ? 'cko-payment-card' : 'cko-payment-card-unselect'}>
            <Stack direction="row" sx={{ alignItems: 'center', position: 'relative' }}>
              <Avatar src={cur.logo} alt={cur.name} sx={{ width: 40, height: 40, mr: '12px' }} />
              <div>
                <Typography sx={{ fontSize: 16, color: 'text.primary', fontWeight: 500 }}>{cur.symbol}</Typography>
                <Typography sx={{ color: 'text.secondary', fontSize: 14 }}>{methodName}</Typography>
              </div>
              <Radio checked={selected} sx={{ position: 'absolute', right: 0 }} />
            </Stack>
          </Card>
        );
      })}
    </CurrencyRoot>
  );
}
