import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { toast } from 'react-hot-toast';
import { StockRoom } from '@/types';
import EditStockSections from '@/Components/modals/EditStockSections';

interface Props {
    room: StockRoom;
    onClose: () => void;
    onUpdated: () => void;
}

export default function EditRoomModal({ room, onClose, onUpdated }: Props) {
    const [data, setData] = useState<StockRoom>(room);
    const [activePosition, setActivePosition] = useState<() => any | null>(null);

    useEffect(() => {
        setData(room);
    }, [room]);

    const reload = async () => {
        try {
            const resp = await axios.get<StockRoom>(`/api/stock-rooms/${room.room_id}`, { withCredentials: true });
            setData(resp.data);
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to reload room');
        }
    };

    const addLine = async () => {
        try {
            const newIndex = data.lines.length + 1;
            await axios.post('/api/stock-lines', {
                room_id: room.room_id,
                line_symbol: `${newIndex}`,
                line_name: `Line ${newIndex}`
            }, { withCredentials: true });
            await reload();
            toast.success('Line added');
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to add line');
        }
    };

    const addRack = async (line_id: number, line_symbol: string, line_name: string) => {
        try {
            const line = data.lines.find(l => l.line_id === line_id);
            const newIndex = line?.racks.length! + 1;
            await axios.post('/api/stock-racks', {
                line_id,
                rack_symbol: `${newIndex}`,
                rack_name: `Rack ${newIndex}`
            }, { withCredentials: true });
            await reload();
            toast.success('Rack added');
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to add rack');
        }
    };

    const addShelf = async (rack_id: number, rack_symbol: string, rack_name: string) => {
        try {
            const rack = data.lines
                .flatMap(l => l.racks)
                .find(r => r.rack_id === rack_id);
            const newIndex = rack?.shelves.length! + 1;
            await axios.post('/api/stock-shelves', {
                rack_id,
                shelf_symbol: `${newIndex}`,
                shelf_name: `Shelf ${newIndex}`
            }, { withCredentials: true });
            await reload();
            toast.success('Shelf added');
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to add shelf');
        }
    };

    const addPosition = async (shelf_id: number, shelf_symbol: string, shelf_name: string) => {
        try {
            const shelf = data.lines
                .flatMap(l => l.racks)
                .flatMap(r => r.shelves)
                .find(s => s.shelf_id === shelf_id);
            const newIndex = shelf?.positions.length! + 1;
            await axios.post('/api/stock-positions', {
                shelf_id,
                position_symbol: `${newIndex}`,
                position_name: `Position ${newIndex}`,
                capacity: 0
            }, { withCredentials: true });
            await reload();
            toast.success('Position added');
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to add position');
        }
    };

    return (
        <div className="modal-box max-w-6xl p-6 relative">
            <h3 className="text-xl font-bold mb-4 flex justify-between items-center">
                <span>Edit Room: {data.room_name}</span>
                <button className="btn btn-sm btn-outline" onClick={addLine}>+ Add Line</button>
            </h3>

            <div className="space-y-2 max-h-[60vh] overflow-y-auto">
                {data.lines.map(line => (
                    <details key={line.line_id} className="border rounded p-2">
                        <summary className="flex justify-between items-center font-semibold">
                            <span>{line.line_name}</span>
                            <button className="btn btn-xs btn-outline" onClick={() => addRack(line.line_id, line.line_symbol, line.line_name)}>
                                + Add Rack
                            </button>
                        </summary>

                        {line.racks.map(rack => (
                            <details key={rack.rack_id} className="ml-4 border rounded p-2">
                                <summary className="flex justify-between items-center">
                                    <span>{rack.rack_name}</span>
                                    <button className="btn btn-xxs btn-outline" onClick={() => addShelf(rack.rack_id, rack.rack_symbol, rack.rack_name)}>
                                        + Add Shelf
                                    </button>
                                </summary>

                                {rack.shelves.map(shelf => (
                                    <details key={shelf.shelf_id} className="ml-4 border rounded p-2">
                                        <summary className="flex justify-between items-center">
                                            <span>{shelf.shelf_name}</span>
                                            <button className="btn btn-xxs btn-outline" onClick={() => addPosition(shelf.shelf_id, shelf.shelf_symbol, shelf.shelf_name)}>
                                                + Add Position
                                            </button>
                                        </summary>

                                        <ul className="ml-4">
                                            {shelf.positions.map(pos => (
                                                <li key={pos.position_id} className="flex justify-between items-center py-1">
                                                    <span>{pos.position_name}</span>
                                                    <button
                                                        className="btn btn-xs btn-outline"
                                                        onClick={() => setActivePosition(() => () => pos)}
                                                    >
                                                        Edit Sections
                                                    </button>
                                                </li>
                                            ))}
                                        </ul>
                                    </details>
                                ))}
                            </details>
                        ))}
                    </details>
                ))}
            </div>

            <div className="flex justify-end space-x-2 mt-4">
                <button onClick={onClose} className="btn btn-outline">Close</button>
            </div>

            {activePosition && (
                <EditStockSections
                    selectedPosition={activePosition}
                    onClose={() => {
                        setActivePosition(null);
                        reload();
                    }}
                />
            )}
        </div>
    );
}
