import { useQueries } from '@tanstack/react-query'
import { Box, Paper, Typography, Button, Grid, Skeleton } from '@mui/material'
import { Refresh } from '@mui/icons-material'
import Chart from './Chart'
import RealtimePrice from './RealtimePrice'
import { marketDataApi } from '../api/marketData'

interface ChartGridProps {
    symbols: string[]
    onAnalyze?: (symbol: string) => void
    isAnalyzing?: boolean
}

export default function ChartGrid({ symbols, onAnalyze, isAnalyzing }: ChartGridProps) {
    // Fetch OHLCV data for all symbols in parallel
    const ohlcvQueries = useQueries({
        queries: symbols.map((symbol) => ({
            queryKey: ['market-data', symbol],
            queryFn: () => marketDataApi.getOHLCV(symbol),
            refetchInterval: 60000,
            staleTime: 30000,
        })),
    })

    // Determine grid columns based on symbol count
    const getGridColumns = () => {
        if (symbols.length === 1) return 12
        if (symbols.length === 2) return 6
        return 6 // 2x2 grid for 3-4 symbols
    }

    const chartHeight = symbols.length === 1 ? 400 : 280

    return (
        <Grid container spacing={2}>
            {symbols.map((symbol, index) => {
                const query = ohlcvQueries[index]
                const isLoading = query?.isLoading
                const data = query?.data

                return (
                    <Grid item xs={12} md={getGridColumns()} key={symbol}>
                        <Paper
                            sx={{
                                p: 2,
                                height: '100%',
                                transition: 'all 0.3s ease',
                                '&:hover': {
                                    boxShadow: 4,
                                },
                            }}
                        >
                            {/* Header */}
                            <Box
                                sx={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'flex-start',
                                    mb: 1.5,
                                    flexWrap: 'wrap',
                                    gap: 1,
                                }}
                            >
                                <Box>
                                    <Typography
                                        variant="subtitle1"
                                        sx={{ fontWeight: 600, lineHeight: 1.2 }}
                                    >
                                        {symbol}
                                    </Typography>
                                    <RealtimePrice
                                        symbol={symbol}
                                        size="small"
                                        showProvider={false}
                                        showChange={true}
                                    />
                                </Box>
                                {onAnalyze && (
                                    <Button
                                        size="small"
                                        variant="outlined"
                                        startIcon={<Refresh />}
                                        onClick={() => onAnalyze(symbol)}
                                        disabled={isAnalyzing}
                                        sx={{ minWidth: 'auto', px: 1.5 }}
                                    >
                                        Analyze
                                    </Button>
                                )}
                            </Box>

                            {/* Chart */}
                            {isLoading ? (
                                <Skeleton
                                    variant="rectangular"
                                    width="100%"
                                    height={chartHeight}
                                    sx={{ borderRadius: 1 }}
                                />
                            ) : data && Array.isArray(data) && data.length > 0 ? (
                                <Box sx={{ height: chartHeight }}>
                                    <Chart data={data} height={chartHeight} />
                                </Box>
                            ) : (
                                <Box
                                    sx={{
                                        height: chartHeight,
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        bgcolor: 'action.hover',
                                        borderRadius: 1,
                                    }}
                                >
                                    <Typography color="text.secondary" variant="body2">
                                        No data for {symbol}
                                    </Typography>
                                </Box>
                            )}
                        </Paper>
                    </Grid>
                )
            })}
        </Grid>
    )
}
