import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, LayoutGrid, ArrowRight } from 'lucide-react';
import { LayoutSection, LayoutRoom } from '../../../stores/layoutStore';

interface AddSectionProps {
    room: LayoutRoom;
    isOpen: boolean;
    onClose: () => void;
    onSave: (section: Omit<LayoutSection, 'id'>) => void;
    editSection?: LayoutSection;
}

const PIXELS_PER_FOOT = 20;

export function AddSectionDialog({ room, isOpen, onClose, onSave, editSection }: AddSectionProps) {
    if (!isOpen) return null;

    const [name, setName] = useState('New Section');
    const [code, setCode] = useState('SEC-1');
    const [type, setType] = useState<LayoutSection['type']>('TABLE');
    const [rows, setRows] = useState(1);
    const [columns, setColumns] = useState(1);
    const [tiers, setTiers] = useState(1);
    const [width, setWidth] = useState(4); // feet
    const [height, setHeight] = useState(8); // feet
    const [spacing, setSpacing] = useState(12); // inches

    // Reset when opening
    useEffect(() => {
        if (isOpen) {
            if (editSection) {
                setName(editSection.name);
                setCode(editSection.code);
                setType(editSection.type);
                setRows(editSection.rows);
                setColumns(editSection.columns);
                setTiers(editSection.tiers || 1);
                setWidth(Math.round(editSection.size.width / PIXELS_PER_FOOT));
                setHeight(Math.round(editSection.size.height / PIXELS_PER_FOOT));
                setSpacing(editSection.spacing);
            } else {
                setName(`Section ${Math.floor(Math.random() * 100)}`);
                setCode(`SEC-${Math.floor(Math.random() * 100)}`);
                setType('TABLE');
                setRows(1);
                setColumns(5);
                setTiers(1);
                setWidth(4);
                setHeight(10);
                setSpacing(12);
            }
        }
    }, [isOpen, editSection]);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        onSave({
            roomId: room.id,
            name,
            code,
            type,
            rows,
            columns,
            tiers,
            spacing,
            size: {
                width: width * PIXELS_PER_FOOT,
                height: height * PIXELS_PER_FOOT
            },
            position: editSection?.position || { x: 20, y: 20 }
        });
        onClose();
    };

    return createPortal(
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
            <div className="w-full max-w-md bg-slate-900 border border-slate-700 rounded-xl shadow-2xl flex flex-col max-h-[90vh]">
                {/* Header */}
                <div className="flex items-center justify-between p-4 border-b border-white/10">
                    <h2 className="font-bold text-white flex items-center gap-2">
                        <LayoutGrid className="text-emerald-400" size={20} />
                        {editSection ? 'Edit Section' : 'Add Section'}
                    </h2>
                    <button onClick={onClose} className="text-[var(--color-text-tertiary)] hover:text-white transition-colors">
                        <X size={20} />
                    </button>
                </div>

                {/* Body */}
                <form onSubmit={handleSubmit} className="p-4 space-y-4 overflow-y-auto">
                    {/* Basic Info */}
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Name</label>
                            <input
                                type="text"
                                value={name}
                                onChange={e => setName(e.target.value)}
                                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white focus:border-emerald-500 outline-none"
                                required
                            />
                        </div>
                        <div>
                            <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Code</label>
                            <input
                                type="text"
                                value={code}
                                onChange={e => setCode(e.target.value.toUpperCase())}
                                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white font-mono focus:border-emerald-500 outline-none"
                                required
                            />
                        </div>
                    </div>

                    {/* Type */}
                    <div>
                        <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Type</label>
                        <select
                            value={type}
                            onChange={e => setType(e.target.value as any)}
                            className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                        >
                            <option value="TABLE">Grow Table (Rolling)</option>
                            <option value="RACK">Vertical Rack</option>
                            <option value="TRAY">Propagation Tray</option>
                            <option value="HANGER">Drying Hanger</option>
                            <option value="FLOOR">Floor Layout</option>
                        </select>
                    </div>

                    {/* Dimensions */}
                    <div className="bg-slate-800/50 p-3 rounded-lg border border-slate-700/50">
                        <label className="block text-xs text-emerald-400 mb-2 font-medium">Physical Dimensions</label>
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Width (ft)</label>
                                <input
                                    type="number"
                                    value={width}
                                    onChange={e => setWidth(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="1"
                                />
                            </div>
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Length/Height (ft)</label>
                                <input
                                    type="number"
                                    value={height}
                                    onChange={e => setHeight(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="1"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Grid Configuration */}
                    <div className="bg-slate-800/50 p-3 rounded-lg border border-slate-700/50">
                        <label className="block text-xs text-emerald-400 mb-2 font-medium">Plant Slots (Position Grid)</label>
                        <div className="grid grid-cols-3 gap-3">
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Rows</label>
                                <input
                                    type="number"
                                    value={rows}
                                    onChange={e => setRows(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="1"
                                />
                            </div>
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Columns</label>
                                <input
                                    type="number"
                                    value={columns}
                                    onChange={e => setColumns(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="1"
                                />
                            </div>
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Tiers (Z)</label>
                                <input
                                    type="number"
                                    value={tiers}
                                    onChange={e => setTiers(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="1"
                                />
                            </div>
                            <div>
                                <label className="block text-xs text-[var(--color-text-tertiary)] mb-1">Spacing (in)</label>
                                <input
                                    type="number"
                                    value={spacing}
                                    onChange={e => setSpacing(Number(e.target.value))}
                                    className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white outline-none"
                                    min="0"
                                />
                            </div>
                        </div>
                        <div className="mt-2 text-xs text-[var(--color-text-tertiary)] flex items-center gap-1">
                            <ArrowRight size={12} />
                            Total Capacity: <span className="text-white font-bold">{rows * columns * tiers}</span> positions
                            {tiers > 1 && <span className="text-[var(--color-text-tertiary)] ml-1">({rows * columns} per tier)</span>}
                        </div>
                    </div>

                </form>

                {/* Footer */}
                <div className="p-4 border-t border-white/10 flex justify-end gap-2">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-sm text-[var(--color-text-tertiary)] hover:text-white transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSubmit}
                        className="px-4 py-2 bg-[var(--color-primary)] hover:bg-[var(--color-primary)] text-white text-sm font-medium rounded-lg transition-colors"
                    >
                        {editSection ? 'Save Changes' : 'Create Section'}
                    </button>
                </div>
            </div>
        </div>,
        document.body
    );
}
