import { useState, useRef } from 'react';
import { useConnectionStore } from '../../store/connectionStore';

interface Position {
    x: number;
    y: number;
}

interface DraggableElements {
    [key: string]: Position;
}

export const ConnectionDiagram = () => {
    const { support, beam, angle, bolts, connectionType } = useConnectionStore();
    const [draggedElement, setDraggedElement] = useState<string | null>(null);
    const [elementPositions, setElementPositions] = useState<DraggableElements>({});
    const [isLocked, setIsLocked] = useState(true);
    const svgRef = useRef<SVGSVGElement>(null);

    // Scaling
    const scale = 10;
    const boltSpacing = bolts.spacing * scale;
    const angleThickness = angle.thickness * scale;
    const edgeDistV = angle.edgeDistanceVertical * scale;
    const edgeDistH = angle.edgeDistanceHorizontal * scale;
    const beamGap = beam.gapFromSupport * scale;
    const angleLeg = angle.legOnSupport * scale;

    const boltRows = bolts.numberOfRows;
    const boltGroupHeight = (boltRows - 1) * boltSpacing;
    const totalConnectionHeight = edgeDistV * 2 + boltGroupHeight;
    const startY = 60;

    // Engineering Style Colors
    const colors = {
        support: '#40E0D0', // Turquoise/Cyan
        beam: '#00FF7F',    // SpringGreen
        angle: '#FFFF00',   // Yellow
        plate: '#FFA500',   // Orange for single-plate
        tee: '#87CEEB',     // SkyBlue for Tee
        bolt: '#FF0000',    // Red
        line: '#000000'
    };

    // Drag Logic
    const handleMouseDown = (elementId: string) => {
        if (!isLocked) setDraggedElement(elementId);
    };

    const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
        if (draggedElement && svgRef.current && !isLocked) {
            const svg = svgRef.current;
            const pt = svg.createSVGPoint();
            pt.x = e.clientX;
            pt.y = e.clientY;
            const svgP = pt.matrixTransform(svg.getScreenCTM()?.inverse());
            setElementPositions(prev => ({ ...prev, [draggedElement]: { x: svgP.x, y: svgP.y } }));
        }
    };

    const handleMouseUp = () => setDraggedElement(null);
    const getPos = (id: string, def: Position) => elementPositions[id] || def;

    // Helper: Draggable Text
    const DraggableText = ({ id, x, y, children, fontSize = "11", fontWeight = "normal", textDecoration = "none" }: any) => {
        const pos = getPos(id, { x, y });
        return (
            <text
                x={pos.x}
                y={pos.y}
                fontSize={fontSize}
                fontWeight={fontWeight}
                textDecoration={textDecoration}
                fill="black"
                style={{ cursor: isLocked ? 'default' : 'move' }}
                onMouseDown={(e) => { e.stopPropagation(); handleMouseDown(id); }}
            >
                {children}
            </text>
        );
    };

    // Helper: Dimension Line
    const DimLine = ({ id, x1, y1, x2, y2, text, textPos, arrows = 'both' }: any) => {
        const p1 = getPos(`${id}-p1`, { x: x1, y: y1 });
        const p2 = getPos(`${id}-p2`, { x: x2, y: y2 });
        const tp = getPos(`${id}-text`, textPos);

        return (
            <g>
                <line x1={x1} y1={y1} x2={p1.x} y2={p1.y} stroke="black" strokeWidth="0.5" />
                <line x1={x2} y1={y2} x2={p2.x} y2={p2.y} stroke="black" strokeWidth="0.5" />
                <line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke="black" strokeWidth="0.5"
                    markerStart={arrows !== 'end' ? "url(#arrowhead)" : undefined}
                    markerEnd={arrows !== 'start' ? "url(#arrowhead)" : undefined} />
                <text x={tp.x} y={tp.y} fontSize="10" fill="black" textAnchor="middle" dominantBaseline="middle"
                    style={{ cursor: isLocked ? 'default' : 'move' }}
                    onMouseDown={(e) => { e.stopPropagation(); handleMouseDown(`${id}-text`); }}>
                    {text}
                </text>
            </g>
        );
    };

    const renderFrontConnection = () => {
        switch (connectionType) {
            case 'double-angle':
                return (
                    <g>
                        <rect x={110} y={startY + edgeDistV - 10} width={angleThickness} height={totalConnectionHeight + 20} fill={colors.angle} stroke="black" strokeWidth="1" />
                        <rect x={150} y={startY + edgeDistV - 10} width={angleThickness} height={totalConnectionHeight + 20} fill={colors.angle} stroke="black" strokeWidth="1" />
                    </g>
                );
            case 'single-plate':
                return <rect x={130} y={startY + edgeDistV - 10} width={angleThickness} height={totalConnectionHeight + 20} fill={colors.plate} stroke="black" strokeWidth="1" />;
            case 'tee':
                return (
                    <g>
                        <rect x={110} y={startY + edgeDistV - 20} width={80} height={totalConnectionHeight + 40} fill={colors.tee} stroke="black" strokeWidth="1" rx="2" />
                        <line x1={150} y1={startY + edgeDistV - 20} x2={150} y2={startY + edgeDistV + totalConnectionHeight + 20} stroke="black" strokeWidth="1" />
                    </g>
                );
            case 'single-angle':
            default:
                return <rect x={110} y={startY + edgeDistV - 10} width={angleThickness} height={totalConnectionHeight + 20} fill={colors.angle} stroke="black" strokeWidth="1" />;
        }
    };

    return (
        <div style={{ background: 'white', padding: '20px', borderRadius: '4px', border: '1px solid #e0e0e0', userSelect: 'none' }}>
            <div style={{ marginBottom: '20px', display: 'flex', gap: '12px', alignItems: 'center' }}>
                <button onClick={() => setIsLocked(!isLocked)} style={{ padding: '6px 12px', background: isLocked ? '#f5f5f5' : '#e3f2fd', color: isLocked ? '#666' : '#1976d2', border: '1px solid #ccc', borderRadius: '4px', cursor: 'pointer', fontWeight: '600', fontSize: '12px' }}>
                    {isLocked ? '🔒 Locked' : '🔓 Unlock'}
                </button>
                {!isLocked && <span style={{ fontSize: '12px', color: '#666' }}>Drag dimensions and labels to customize</span>}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'minmax(300px, 1fr) minmax(300px, 1fr)', gap: '40px' }}>

                {/* --- FRONT VIEW --- */}
                <svg ref={svgRef} width="100%" height="350" viewBox="0 0 350 350" onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
                    <defs><marker id="arrowhead" markerWidth="8" markerHeight="6" refX="8" refY="3" orient="auto"><polygon points="0 0, 8 3, 0 6" fill="black" /></marker></defs>
                    <DraggableText id="fv-title" x={175} y={330} fontSize="14" fontWeight="bold" textDecoration="underline">FRONT VIEW</DraggableText>

                    {/* Support Column */}
                    <rect x="50" y={20} width="80" height="300" fill={colors.support} stroke="black" strokeWidth="1" />
                    <line x1="90" y1={20} x2="90" y2={320} stroke="black" strokeWidth="0.5" />
                    {/* Updated Default Position to Bottom (y=280) */}
                    <DraggableText id="fv-sup-label" x={60} y={280}>Support</DraggableText>
                    <DraggableText id="fv-sup-desig" x={60} y={295}>{support.designation}</DraggableText>

                    {/* Beam (Translucent) */}
                    <rect x={130} y={startY} width="120" height={totalConnectionHeight + 60} fill={colors.beam} stroke="black" strokeWidth="1" opacity="0.8" />
                    <line x1={190} y1={startY - 10} x2={190} y2={startY + totalConnectionHeight + 70} stroke="black" strokeWidth="0.5" strokeDasharray="5,3" />
                    <DraggableText id="fv-beam-label" x={200} y={startY + 10}>CL {beam.designation}</DraggableText>

                    {/* Connection */}
                    {renderFrontConnection()}

                    {/* Bolts */}
                    {Array.from({ length: boltRows }).map((_, i) => (
                        <g key={i}>
                            <circle cx="120" cy={startY + edgeDistV + i * boltSpacing} r="4" fill={colors.bolt} stroke="black" strokeWidth="1" />
                            <circle cx="140" cy={startY + edgeDistV + i * boltSpacing} r="4" fill={colors.bolt} stroke="black" strokeWidth="1" />
                        </g>
                    ))}

                    {/* Dimensions */}
                    <DimLine id="fv-edge" x1="140" y1={startY + edgeDistV} x2="160" y2={startY + edgeDistV} text={`${edgeDistH / scale} in`} textPos={{ x: 175, y: startY + edgeDistV }} arrows="start" />

                    {Array.from({ length: boltRows - 1 }).map((_, i) => (
                        <DimLine key={i} id={`fv-pitch-${i}`}
                            x1="100" y1={startY + edgeDistV + i * boltSpacing}
                            x2="100" y2={startY + edgeDistV + (i + 1) * boltSpacing}
                            text={`${bolts.spacing} in`} textPos={{ x: 80, y: startY + edgeDistV + i * boltSpacing + boltSpacing / 2 }} />
                    ))}
                </svg>

                {/* --- SIDE VIEW --- */}
                <svg width="100%" height="350" viewBox="0 0 350 350">
                    <DraggableText id="sv-title" x={175} y={330} fontSize="14" fontWeight="bold" textDecoration="underline">SIDE VIEW</DraggableText>

                    {/* Support Side */}
                    <rect x="50" y={20} width="40" height="300" fill={colors.support} stroke="black" strokeWidth="1" />
                    {/* Updated Default Position to Left Outside (x=10) */}
                    <DraggableText id="sv-sup-label" x={10} y={150}>Support</DraggableText>
                    <DraggableText id="sv-sup-desig" x={10} y={165}>{support.designation}</DraggableText>

                    {/* Connection Side */}
                    <rect x={90 + beamGap} y={startY} width={angleThickness} height={totalConnectionHeight + 20} fill={connectionType === 'single-plate' ? colors.plate : colors.angle} stroke="black" strokeWidth="1" />

                    {/* Beam Side */}
                    <rect x={90 + beamGap + angleThickness} y={startY + 10} width="160" height={totalConnectionHeight} fill={colors.beam} stroke="black" strokeWidth="1" />

                    {/* Bolts Side */}
                    {Array.from({ length: boltRows }).map((_, i) => (
                        <rect key={i} x={90 + beamGap - 5} y={startY + edgeDistV + i * boltSpacing - 4} width={angleThickness + 10} height={8} fill={colors.bolt} stroke="black" strokeWidth="0.5" />
                    ))}

                    {/* Dimensions */}
                    <DimLine id="sv-gap" x1="90" y1={startY - 15} x2={90 + beamGap} y2={startY - 15} text={`${beam.gapFromSupport} in`} textPos={{ x: 90 + beamGap / 2, y: startY - 25 }} />
                </svg>

                {/* --- TOP VIEW --- */}
                <div style={{ gridColumn: 'span 2', display: 'flex', justifyContent: 'center' }}>
                    <svg width="400" height="200" viewBox="0 0 400 200">
                        <DraggableText id="tv-title" x={200} y={190} fontSize="14" fontWeight="bold" textDecoration="underline">TOP VIEW</DraggableText>

                        {/* Support Top */}
                        <rect x="50" y="50" width="20" height="100" fill={colors.support} stroke="black" strokeWidth="1" />
                        <rect x="70" y="90" width="40" height="20" fill={colors.support} stroke="black" strokeWidth="1" />

                        <DraggableText id="tv-sup-label" x={30} y={40}>Support {support.designation}</DraggableText>

                        {/* Angles/Plate Top */}
                        {connectionType === 'double-angle' ? (
                            <>
                                <rect x={110 + beamGap} y={80} width={angleLeg} height={angleThickness} fill={colors.angle} stroke="black" strokeWidth="1" />
                                <rect x={110 + beamGap} y={120 - angleThickness} width={angleLeg} height={angleThickness} fill={colors.angle} stroke="black" strokeWidth="1" />
                            </>
                        ) : (
                            <rect x={110 + beamGap} y={90} width={angleLeg} height={angleThickness} fill={colors.angle} stroke="black" strokeWidth="1" />
                        )}

                        {/* Beam Top */}
                        <rect x={110 + beamGap + angleThickness} y={98} width="150" height="4" fill={colors.beam} stroke="black" strokeWidth="1" />

                        {/* Dimensions */}
                        <DimLine id="tv-leg" x1={110 + beamGap} y1={130} x2={110 + beamGap + angleLeg} y2={130} text={`${angle.legOnSupport} in`} textPos={{ x: 110 + beamGap + angleLeg / 2, y: 145 }} />

                    </svg>
                </div>

            </div>
        </div>
    );
};
