import React, { Suspense, useEffect, useRef, useState, useMemo } from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, Center, Environment, Text } from '@react-three/drei';
import * as THREE from 'three';
import JSZip from 'jszip';
import { AppConfig, GeneratedPart, LayoutSplits, PerforationConfig } from '../types';
import { createBinGeometry, generateSTL, exportSTL } from '../services/geometryGenerator';
import { Download, Package, Info, Loader2, Share2, Check, Ruler } from 'lucide-react';
import { generateShareUrl } from '../utils/share';

// --- DrawerFrame (Каркас ящика) ---
const DrawerFrame = ({ config }: { config: AppConfig }) => {
    const { width, depth, height } = config.drawer;
    const offset = 0.5;
    return (
        <group position={[width / 2, height / 2, depth / 2]}>
            <lineSegments>
                <edgesGeometry args={[new THREE.BoxGeometry(width + offset, height + offset, depth + offset)]} />
                <lineBasicMaterial color="#475569" />
            </lineSegments>
        </group>
    )
}

// --- BinMesh (Ячейка) ---
interface BinMeshProps {
    part: GeneratedPart;
    thickness: number;
    cornerRadius: number;
    perforation: PerforationConfig;
    isSelected: boolean;
    onClick: () => void;
}

const BinMesh: React.FC<BinMeshProps> = ({ part, thickness, cornerRadius, perforation, isSelected, onClick }) => {
    // 1. Создаем геометрию, учитывая ВНУТРЕННИЕ ПЕРЕГОРОДКИ
    const geometry = useMemo(() => {
        return createBinGeometry(
            part.width,
            part.depth,
            part.height,
            thickness,
            cornerRadius,
            part.internalPartitions, // <--- ВАЖНО: передаем перегородки в генератор
            perforation
        );
    }, [part, thickness, cornerRadius, perforation]);

    // 2. Создаем контур выделения (EdgesGeometry)
    // Threshold 20 градусов скрывает линии на плавных скруглениях
    const edgesGeometry = useMemo(() => {
        return new THREE.EdgesGeometry(geometry, 20);
    }, [geometry]);

    // 3. Вычисляем размеры и позиции для каждой под-ячейки
    // 3. Вычисляем размеры и позиции для реальных отсеков (с учетом мерджинга)
    const dimLabels = useMemo(() => {
        const xOffsets = new Set<number>([0, 1]);
        const zOffsets = new Set<number>([0, 1]);

        part.internalPartitions.forEach(p => {
            if (p.axis === 'x') xOffsets.add(p.offset);
            if (p.axis === 'y') zOffsets.add(p.offset);
        });

        const xSplits = Array.from(xOffsets).sort((a, b) => a - b);
        const zSplits = Array.from(zOffsets).sort((a, b) => a - b);

        const numCols = xSplits.length - 1;
        const numRows = zSplits.length - 1;
        if (numCols === 0 || numRows === 0) return [];

        // Union-Find для объединения ячеек, не разделенных стеной
        const parent = new Int32Array(numCols * numRows).map((_, i) => i);
        const find = (i: number): number => {
            if (parent[i] === i) return i;
            parent[i] = find(parent[i]);
            return parent[i];
        }
        const union = (i: number, j: number) => {
            const rootI = find(i);
            const rootJ = find(j);
            if (rootI !== rootJ) parent[rootJ] = rootI;
        }
        const getIdx = (c: number, r: number) => r * numCols + c;

        // Вертикальные границы (X)
        for (let i = 0; i < numCols - 1; i++) {
            const boundaryX = xSplits[i + 1];
            for (let j = 0; j < numRows; j++) {
                const zMid = (zSplits[j] + zSplits[j + 1]) / 2;
                // Проверяем наличие перегородки axis='x'
                const isBlocked = part.internalPartitions.some(p =>
                    p.axis === 'x' &&
                    Math.abs(p.offset - boundaryX) < 0.001 &&
                    (p.min ?? 0) <= zMid && (p.max ?? 1) >= zMid
                );
                if (!isBlocked) union(getIdx(i, j), getIdx(i + 1, j));
            }
        }

        // Горизонтальные границы (Z/Y)
        for (let j = 0; j < numRows - 1; j++) {
            const boundaryZ = zSplits[j + 1];
            for (let i = 0; i < numCols; i++) {
                const xMid = (xSplits[i] + xSplits[i + 1]) / 2;
                // Проверяем наличие перегородки axis='y'
                const isBlocked = part.internalPartitions.some(p =>
                    p.axis === 'y' &&
                    Math.abs(p.offset - boundaryZ) < 0.001 &&
                    (p.min ?? 0) <= xMid && (p.max ?? 1) >= xMid
                );
                if (!isBlocked) union(getIdx(i, j), getIdx(i, j + 1));
            }
        }

        // Агрегируем регионы
        const regions: Record<number, { minC: number, maxC: number, minR: number, maxR: number }> = {};
        for (let j = 0; j < numRows; j++) {
            for (let i = 0; i < numCols; i++) {
                const root = find(getIdx(i, j));
                if (!regions[root]) regions[root] = { minC: i, maxC: i, minR: j, maxR: j };
                else {
                    const r = regions[root];
                    r.minC = Math.min(r.minC, i);
                    r.maxC = Math.max(r.maxC, i);
                    r.minR = Math.min(r.minR, j);
                    r.maxR = Math.max(r.maxR, j);
                }
            }
        }

        return Object.values(regions).map((r, idx) => {
            const fXStart = xSplits[r.minC];
            const fXEnd = xSplits[r.maxC + 1];
            const fZStart = zSplits[r.minR];
            const fZEnd = zSplits[r.maxR + 1];

            const fracW = fXEnd - fXStart;
            const fracD = fZEnd - fZStart;

            const dimX = Math.max(0, fracW * (part.width - thickness) - thickness);
            const dimZ = Math.max(0, fracD * (part.depth - thickness) - thickness);

            const cx = -part.width / 2 + (fXStart + fXEnd) / 2 * part.width;
            const cz = -part.depth / 2 + (fZStart + fZEnd) / 2 * part.depth;

            return {
                key: `region-${idx}`,
                pos: [cx, thickness + 0.2, cz] as [number, number, number],
                text: `${dimX.toFixed(0)} x ${dimZ.toFixed(0)}`
            };
        });
    }, [part, thickness]);

    return (
        <group
            position={[part.x + part.width / 2, 0, part.y + part.depth / 2]}
            onClick={(e) => { e.stopPropagation(); onClick(); }}
        >
            {/* Сама модель */}
            <mesh geometry={geometry}>
                <meshStandardMaterial
                    color={isSelected ? '#f59e0b' : part.color}
                    roughness={0.5}
                    metalness={0.1}
                    side={THREE.DoubleSide}
                />
            </mesh>

            {/* Текстовые метки размеров внутри каждой ячейки */}
            {dimLabels.map(label => (
                <Text
                    key={label.key}
                    position={label.pos}
                    rotation={[-Math.PI / 2, 0, 0]}
                    fontSize={Math.min(part.width, part.depth) * 0.035}
                    color="#1e293b"
                    anchorX="center"
                    anchorY="middle"
                    characters="0123456789x "
                >
                    {label.text}
                </Text>
            ))}

            {/* Белая подсветка при выборе */}
            {isSelected && (
                <lineSegments geometry={edgesGeometry}>
                    <lineBasicMaterial color="white" linewidth={2} />
                </lineSegments>
            )}
        </group>
    );
};

// --- PreviewStep (Основной компонент) ---
interface Props {
    parts: GeneratedPart[];
    config: AppConfig;
    splits: LayoutSplits;
}

export const PreviewStep: React.FC<Props> = ({ parts, config, splits }) => {
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const [isZipping, setIsZipping] = useState(false);
    const [shareUrlCopied, setShareUrlCopied] = useState(false);
    const itemRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});

    // Скролл к выбранной детали в списке
    useEffect(() => {
        if (selectedId && itemRefs.current[selectedId]) {
            itemRefs.current[selectedId]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }, [selectedId]);

    // Скачивание одной детали
    const handleDownload = (part: GeneratedPart) => {
        const geometry = createBinGeometry(
            part.width,
            part.depth,
            part.height,
            config.wallThickness,
            config.cornerRadius,
            part.internalPartitions, // <--- ВАЖНО для STL
            config.perforation
        );
        const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
        exportSTL(mesh, `${part.name.replace(/\s+/g, '_')}.stl`);
    };

    // Скачивание всего архивом
    const handleDownloadAll = async () => {
        if (isZipping) return;
        setIsZipping(true);
        try {
            const zip = new JSZip();
            parts.forEach(part => {
                const geometry = createBinGeometry(
                    part.width,
                    part.depth,
                    part.height,
                    config.wallThickness,
                    config.cornerRadius,
                    part.internalPartitions, // <--- ВАЖНО для STL
                    config.perforation
                );
                const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial());
                const stlData = generateSTL(mesh);
                zip.file(`${part.name.replace(/\s+/g, '_')}.stl`, stlData);
            });
            const content = await zip.generateAsync({ type: "blob" });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(content);
            link.download = "PrintFit_Project.zip";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (e: any) {
            alert(`Ошибка архивации: ${e.message}`);
        } finally {
            setIsZipping(false);
        }
    };

    // Поделиться ссылкой
    const handleShare = async () => {
        const url = generateShareUrl(config, splits);
        let success = false;
        try {
            if (navigator.clipboard && navigator.clipboard.writeText) {
                await navigator.clipboard.writeText(url);
                success = true;
            } else { throw new Error('Clipboard API unavailable'); }
        } catch (err) {
            try {
                const textArea = document.createElement("textarea");
                textArea.value = url;
                textArea.style.position = "fixed";
                textArea.style.left = "-9999px";
                textArea.style.top = "0";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                const result = document.execCommand('copy');
                document.body.removeChild(textArea);
                if (result) success = true;
            } catch (e) { console.error("Copy failed", e); }
        }
        if (success) {
            setShareUrlCopied(true);
            setTimeout(() => setShareUrlCopied(false), 3000);
        } else {
            prompt("Скопируйте ссылку вручную:", url);
        }
    };

    return (
        <div className="flex flex-col h-full">
            {/* Верхняя панель: Размеры + Поделиться */}
            <div className="flex flex-col xl:flex-row justify-between items-center bg-slate-800/80 p-4 rounded-xl border border-slate-700 mb-4 gap-4 backdrop-blur-sm shadow-lg">

                <div className="flex flex-wrap items-center gap-6 justify-center md:justify-start">
                    <div className="hidden md:flex items-center gap-2 text-gray-300 mr-2">
                        <Ruler className="text-primary" size={20} />
                        <span className="font-medium text-sm uppercase tracking-wide opacity-70">Размеры ящика:</span>
                    </div>
                    <div className="flex flex-wrap gap-6 font-mono text-white items-baseline">
                        <div className="flex items-baseline gap-2">
                            <span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Ширина:</span>
                            <span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.width}</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                            <span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Глубина:</span>
                            <span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.depth}</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                            <span className="text-slate-500 text-sm font-bold uppercase tracking-wider">Высота:</span>
                            <span className="text-2xl font-bold text-white drop-shadow-sm">{config.drawer.height}</span>
                        </div>
                        <span className="text-sm text-slate-500 font-bold self-baseline">мм</span>
                    </div>
                </div>

                <button
                    onClick={handleShare}
                    className={`
                  flex items-center gap-2 px-6 py-3 rounded-lg text-sm font-bold transition-all border shadow-md active:scale-95 shrink-0
                  ${shareUrlCopied
                            ? 'bg-green-600 border-green-500 text-white shadow-green-900/20'
                            : 'bg-blue-600 hover:bg-blue-500 border-blue-500 text-white shadow-blue-900/20'
                        }
              `}
                >
                    {shareUrlCopied ? <Check size={18} /> : <Share2 size={18} />}
                    {shareUrlCopied ? 'СКОПИРОВАНО!' : 'Поделиться'}
                </button>
            </div>

            <div className="flex flex-col lg:flex-row h-full gap-6 relative flex-1 min-h-0">
                {/* 3D Просмотр */}
                <div className="flex-1 bg-slate-900 rounded-xl overflow-hidden shadow-2xl border border-slate-800 relative min-h-[400px]">
                    <div className="absolute top-4 right-4 z-10 bg-black/60 p-3 rounded-lg text-xs text-gray-300 backdrop-blur pointer-events-none border border-slate-700">
                        <div className="flex items-center gap-2 mb-1 text-primary font-bold">
                            <Info size={14} /> Управление
                        </div>
                        <ul className="space-y-1">
                            <li>• ЛКМ: Вращение</li>
                            <li>• ПКМ: Перемещение</li>
                            <li>• Скролл: Масштаб</li>
                        </ul>
                    </div>

                    <Canvas
                        shadows
                        dpr={[1, 2]}
                        camera={{
                            position: [config.drawer.width * 1.5, config.drawer.height * 3, config.drawer.depth * 1.5],
                            fov: 45,
                            near: 1,
                            far: 20000
                        }}
                    >
                        <Suspense fallback={null}>
                            <color attach="background" args={['#0f172a']} />
                            <ambientLight intensity={0.7} />
                            <directionalLight position={[100, 200, 50]} intensity={1.2} />
                            <Environment preset="city" />
                            <Center>
                                <group>
                                    <DrawerFrame config={config} />
                                    {parts.map(part => (
                                        <BinMesh
                                            key={part.id}
                                            part={part}
                                            thickness={config.wallThickness}
                                            cornerRadius={config.cornerRadius || 0}
                                            perforation={config.perforation}
                                            isSelected={selectedId === part.id}
                                            onClick={() => setSelectedId(part.id)}
                                        />
                                    ))}
                                </group>
                            </Center>
                            <OrbitControls makeDefault minDistance={10} maxDistance={10000} />
                        </Suspense>
                    </Canvas>
                </div>

                {/* Боковая панель (Сетка) */}
                <div className="w-full lg:w-96 bg-slate-900 p-6 rounded-xl border border-slate-800 flex flex-col h-full shadow-xl">
                    <div className="flex justify-between items-center mb-6 shrink-0">
                        <h2 className="text-xl font-bold flex items-center gap-2 text-primary">
                            <Package size={24} /> Детали ({parts.length})
                        </h2>
                        <button
                            onClick={handleDownloadAll}
                            disabled={isZipping || parts.length === 0}
                            className="bg-slate-700 hover:bg-slate-600 text-white px-3 py-1.5 rounded-md text-sm font-medium flex items-center gap-1 transition-all"
                        >
                            {isZipping ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}
                            Архив
                        </button>
                    </div>

                    <div className="flex-1 overflow-y-auto pr-1 custom-scrollbar">
                        <div className="grid grid-cols-2 gap-3 pb-4">
                            {parts.map(part => (
                                <div
                                    key={part.id}
                                    ref={(el) => { itemRefs.current[part.id] = el }}
                                    className={`
                            p-3 rounded-lg border transition-all cursor-pointer group flex flex-col gap-2 relative overflow-hidden
                            ${selectedId === part.id
                                            ? 'bg-slate-800 border-accent shadow-md shadow-accent/10 ring-1 ring-accent'
                                            : 'bg-slate-800/50 border-slate-700 hover:border-slate-500 hover:bg-slate-800'
                                        }
                          `}
                                    onClick={() => setSelectedId(part.id)}
                                >
                                    {/* Индикатор цвета */}
                                    <div
                                        className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-white/5 to-transparent rounded-bl-3xl pointer-events-none"
                                        style={{ backgroundColor: part.color, opacity: 0.1 }}
                                    />

                                    {/* Заголовок */}
                                    <div className="flex items-center justify-between z-10">
                                        <span className="font-bold text-gray-200 text-xs truncate" title={part.name}>
                                            {part.name}
                                        </span>
                                        <div
                                            className="w-2.5 h-2.5 rounded-full border border-white/20 shadow-sm"
                                            style={{ backgroundColor: part.color }}
                                        />
                                    </div>

                                    {/* Размеры */}
                                    <div className="text-[10px] text-gray-400 font-mono z-10">
                                        {part.width.toFixed(0)} × {part.depth.toFixed(0)} × {part.height.toFixed(0)}
                                    </div>

                                    {/* Кнопка скачивания */}
                                    <button
                                        onClick={(e) => { e.stopPropagation(); handleDownload(part); }}
                                        className="w-full py-1.5 bg-slate-700 hover:bg-primary hover:text-white text-gray-300 rounded text-xs flex items-center justify-center gap-1.5 transition-colors font-medium border border-slate-600 hover:border-primary z-10 mt-1"
                                    >
                                        <Download size={12} /> STL
                                    </button>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};