import { useParams, useNavigate } from 'react-router-dom';
import TableForm from '../components/TableForm/TableForm';
import { useEffect, useRef, useState } from 'react';
import { TablesApi } from '../api/tables';
import { toast } from 'react-toastify';
import { createPortal } from 'react-dom';
import {
    NameTask,
    TaskInfoContainer,
} from '../components/common/SwitchFormTask/SwitchFormTask.style';
import { PrimaryButton } from '../components/common/Buttons/Buttons';

// Data for tables
const tablesData = {
    'Form1': [
        { 'sheet_name': 'АХР', 'skip_rows': 2, 'n_rows': 2, 'alias': 'AHR' },
        { 'sheet_name': 'Смета_2026', 'skip_rows': 4, 'n_rows': 4, 'alias': 'Estimate_2026' },
        { 'sheet_name': 'АХР_лимит', 'skip_rows': 2, 'n_rows': 2, 'alias': 'AHR_limit' },
    ],
    'Form2': [
        { 'sheet_name': 'АХР_аренда', 'skip_rows': 10, 'n_rows': 4, 'alias': 'AHR_rent' },
        { 'sheet_name': 'АХР_коммунал', 'skip_rows': 10, 'n_rows': 4, 'alias': 'AHR_utilities' },
        { 'sheet_name': 'АХР_охрана', 'skip_rows': 10, 'n_rows': 4, 'alias': 'AHR_security' },
        { 'sheet_name': 'КВ_П', 'skip_rows': 6, 'n_rows': 3, 'alias': 'KV_P' },
        { 'sheet_name': 'Отч.9ф', 'skip_rows': 8, 'n_rows': 3, 'alias': 'Report_9f' },
        { 'sheet_name': 'Операц', 'skip_rows': 6, 'n_rows': 3, 'alias': 'Operational' },
    ]
};

export default function TablesTest() {
    const navigate = useNavigate();
    const [selectedForm, setSelectedForm] = useState('');
    const [selectedTable, setSelectedTable] = useState('');
    const [availableTables, setAvailableTables] = useState([]);
    const [selectedTableData, setSelectedTableData] = useState(null);

    // Handle form selection change
    const handleFormChange = (event) => {
        const formValue = event.target.value;
        setSelectedForm(formValue);
        setSelectedTable('');
        setSelectedTableData(null);

        if (formValue) {
            setAvailableTables(tablesData[formValue] || []);
        } else {
            setAvailableTables([]);
        }
    };

    const handleTableChange = (event) => {
        const tableValue = event.target.value;
        setSelectedTable(tableValue);

        if (tableValue) {
            const tableData = availableTables.find(table => table.alias === tableValue);
            setSelectedTableData(tableData);
            console.log('Selected table data:', tableData);
        } else {
            setSelectedTableData(null);
        }
    };

    const handleShowClick = () => {
        if (!selectedForm || !selectedTableData) {
            toast.error('Пожалуйста, выберите форму и таблицу');
            return;
        }

        // Encode the parameters for URL
        const encodedForm = encodeURIComponent(selectedForm);
        const encodedSheetName = encodeURIComponent(selectedTableData.alias);

        // Navigate to the route with parameters
        navigate(`/tables/${encodedForm}/${encodedSheetName}`);
    };

    return (
        <>
            <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
                <h2>Выбор формы и таблицы</h2>

                {/* First dropdown - Form selection */}
                <div style={{ marginBottom: '20px' }}>
                    <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                        Выберите форму:
                    </label>
                    <select
                        value={selectedForm}
                        onChange={handleFormChange}
                        style={{
                            width: '100%',
                            padding: '8px 12px',
                            borderRadius: '4px',
                            border: '1px solid #ccc',
                            fontSize: '14px'
                        }}
                    >
                        <option value="">-- Выберите форму --</option>
                        <option value="Form1">Форма 1</option>
                        <option value="Form2">Форма 2</option>
                    </select>
                </div>

                {/* Second dropdown - Table selection (depends on form) */}
                <div style={{ marginBottom: '20px' }}>
                    <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold' }}>
                        Выберите таблицу:
                    </label>
                    <select
                        value={selectedTable}
                        onChange={handleTableChange}
                        disabled={!selectedForm}
                        style={{
                            width: '100%',
                            padding: '8px 12px',
                            borderRadius: '4px',
                            border: '1px solid #ccc',
                            fontSize: '14px',
                            backgroundColor: !selectedForm ? '#f5f5f5' : 'white',
                            cursor: !selectedForm ? 'not-allowed' : 'pointer'
                        }}
                    >
                        <option value="">-- Выберите таблицу --</option>
                        {availableTables.map((table, index) => (
                            <option key={index} value={table.alias}>
                                {table.sheet_name} ({table.alias})
                            </option>
                        ))}
                    </select>
                </div>

                <PrimaryButton onClick={handleShowClick}>
                    показать
                </PrimaryButton>
            </div>
        </>
    );
}