import { useMemo } from 'react';
import { Line, Text } from '@react-three/drei';
import * as THREE from 'three';

interface GridOverlayProps {
    rows: number;
    columns: number;
    width: number;  // Scaled width
    height: number; // Scaled height
    posX: number;   // Section position X
    posY: number;   // Section position Y (maps to Z in 3D)
    tiers: number;
    currentTier?: number;
    showLabels?: boolean;
    opacity?: number;
}

// Grid colors
const GRID_COLORS = {
    rowLine: '#475569',      // Slate-600
    colLine: '#475569',      // Slate-600
    tierLine: '#64748b',     // Slate-500
    labelText: '#94a3b8',    // Slate-400
    highlight: '#06b6d4',    // Cyan-500
};

export function GridOverlay({
    rows,
    columns,
    width,
    height,
    posX,
    posY,
    tiers,
    currentTier = 1,
    showLabels = true,
    opacity = 0.6,
}: GridOverlayProps) {
    // Calculate spacing
    const colSpacing = width / (columns + 1);
    const rowSpacing = height / (rows + 1);

    // Generate grid line points
    const gridLines = useMemo(() => {
        const lines: Array<{ points: [number, number, number][]; color: string }> = [];

        // Row lines (horizontal, along Z axis in 3D)
        for (let r = 1; r <= rows; r++) {
            const z = posY + r * rowSpacing;
            lines.push({
                points: [
                    [posX, 0.02, z],
                    [posX + width, 0.02, z],
                ],
                color: GRID_COLORS.rowLine,
            });
        }

        // Column lines (vertical, along X axis in 3D)
        for (let c = 1; c <= columns; c++) {
            const x = posX + c * colSpacing;
            lines.push({
                points: [
                    [x, 0.02, posY],
                    [x, 0.02, posY + height],
                ],
                color: GRID_COLORS.colLine,
            });
        }

        return lines;
    }, [rows, columns, width, height, posX, posY, colSpacing, rowSpacing]);

    // Generate row/column labels
    const labels = useMemo(() => {
        if (!showLabels) return [];

        const result: Array<{ text: string; position: [number, number, number]; type: 'row' | 'col' }> = [];

        // Row labels (R1, R2, R3...)
        for (let r = 1; r <= rows; r++) {
            result.push({
                text: `R${r}`,
                position: [posX - 0.3, 0.1, posY + r * rowSpacing],
                type: 'row',
            });
        }

        // Column labels (C1, C2, C3...)
        for (let c = 1; c <= columns; c++) {
            result.push({
                text: `C${c}`,
                position: [posX + c * colSpacing, 0.1, posY + height + 0.25],
                type: 'col',
            });
        }

        return result;
    }, [rows, columns, posX, posY, rowSpacing, colSpacing, height, showLabels]);

    // Tier marker (vertical line showing tier level)
    const tierMarkers = useMemo(() => {
        if (tiers <= 1) return null;

        const markers: Array<{ tier: number; y: number }> = [];
        for (let t = 1; t <= tiers; t++) {
            markers.push({
                tier: t,
                y: 0.4 + (t * 0.6),
            });
        }
        return markers;
    }, [tiers]);

    return (
        <group>
            {/* Grid lines */}
            {gridLines.map((line, i) => (
                <Line
                    key={`grid-${i}`}
                    points={line.points}
                    color={line.color}
                    lineWidth={1}
                    transparent
                    opacity={opacity * 0.5}
                    dashed
                    dashScale={10}
                    dashSize={0.1}
                    gapSize={0.05}
                />
            ))}

            {/* Row/Column labels */}
            {labels.map((label, i) => (
                <Text
                    key={`label-${i}`}
                    position={label.position}
                    rotation={[-Math.PI / 2, 0, 0]}
                    fontSize={0.12}
                    color={GRID_COLORS.labelText}
                    anchorX={label.type === 'row' ? 'right' : 'center'}
                    anchorY="middle"
                    fillOpacity={opacity}
                >
                    {label.text}
                </Text>
            ))}

            {/* Tier indicators (side markers) */}
            {tierMarkers && (
                <group position={[posX - 0.15, 0, posY + height / 2]}>
                    {tierMarkers.map(marker => (
                        <group key={`tier-${marker.tier}`}>
                            {/* Tier line */}
                            <Line
                                points={[
                                    [-0.1, marker.y - 0.1, 0],
                                    [-0.1, marker.y + 0.1, 0],
                                ]}
                                color={marker.tier === currentTier ? GRID_COLORS.highlight : GRID_COLORS.tierLine}
                                lineWidth={2}
                            />
                            {/* Tier label */}
                            <Text
                                position={[-0.25, marker.y, 0]}
                                fontSize={0.1}
                                color={marker.tier === currentTier ? GRID_COLORS.highlight : GRID_COLORS.labelText}
                                anchorX="right"
                                anchorY="middle"
                            >
                                T{marker.tier}
                            </Text>
                        </group>
                    ))}
                </group>
            )}

            {/* Section boundary outline */}
            <Line
                points={[
                    [posX, 0.01, posY],
                    [posX + width, 0.01, posY],
                    [posX + width, 0.01, posY + height],
                    [posX, 0.01, posY + height],
                    [posX, 0.01, posY],
                ]}
                color="#64748b"
                lineWidth={1.5}
                transparent
                opacity={opacity * 0.8}
            />
        </group>
    );
}

// Simplified grid for room-level view
interface RoomGridProps {
    roomWidth: number;
    roomHeight: number;
    posX: number;
    posY: number;
    sectionCount: number;
    totalPlants: number;
}

export function RoomGrid({ roomWidth, roomHeight, posX, posY, sectionCount, totalPlants }: RoomGridProps) {
    return (
        <group>
            {/* Room boundary */}
            <Line
                points={[
                    [posX, 0.005, posY],
                    [posX + roomWidth, 0.005, posY],
                    [posX + roomWidth, 0.005, posY + roomHeight],
                    [posX, 0.005, posY + roomHeight],
                    [posX, 0.005, posY],
                ]}
                color="#334155"
                lineWidth={2}
            />

            {/* Room stats in corner */}
            <Text
                position={[posX + 0.3, 0.15, posY + 0.3]}
                rotation={[-Math.PI / 2, 0, 0]}
                fontSize={0.15}
                color="#cbd5e1"
                anchorX="left"
                anchorY="bottom"
            >
                {sectionCount} sections • {totalPlants} plants
            </Text>
        </group>
    );
}
