import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, ScrollView, TextInput, View } from "react-native";
import { getTables } from "../src/api/tableService";
import AppScreen from "../src/components/ui/AppScreen";
import AppText from "../src/components/ui/AppText";
import { tableSelectStyles as styles } from "../src/styles/tableSelect";
import { gradients } from "../src/theme/gradients";
import { typography } from "../src/theme/typography";

export default function TableSelect() {
    const router = useRouter();
    const [selectedTable, setSelectedTable] = useState<string | null>(null);
    const [newTableName, setNewTableName] = useState("");
    const [inputFocused, setInputFocused] = useState(false);
    const [tables, setTables] = useState<any[]>([]);
    const [gridConfig, setGridConfig] = useState({ rows: 6, columns: 7 });

    useEffect(() => {
        getTables().then((data) => {
            setTables(data);
            // Calcular tamaño de la cuadrícula dinámicamente si quieres
            const maxY = Math.max(...(Array.isArray(data) ? data : []).map((t: any) => t.pos_y ?? 0));
            const maxX = Math.max(...(Array.isArray(data) ? data : []).map((t: any) => t.pos_x ?? 0));
            setGridConfig({ rows: maxY + 1, columns: maxX + 1 });
        });
    }, []);

    const handleConfirm = () => {
        const tableToConfirm = newTableName || selectedTable;
        if (!tableToConfirm) return;
        router.push({
            pathname: "/orders/takenote",
            params: { table: tableToConfirm.toString() },
        });
        setNewTableName("");
        setSelectedTable(null);
    };

    const handleTableSelect = (tableName: string) => {
        setSelectedTable(tableName);
        setNewTableName("");
    };

    const isConfirmDisabled = !(selectedTable || newTableName);

    // Create a 2D grid array
    const renderGrid = () => {
        const grid: (typeof tables[0] | null)[][] = [];
        for (let y = 0; y < gridConfig.rows; y++) {
            grid[y] = [];
            for (let x = 0; x < gridConfig.columns; x++) {
                grid[y][x] = null;
            }
        }
        tables.forEach((table) => {
            if (table.pos_y < gridConfig.rows && table.pos_x < gridConfig.columns) {
                grid[table.pos_y][table.pos_x] = table;
            }
        });
        return grid.map((row, rowIndex) => (
            <View key={rowIndex} style={styles.gridRow}>
                {row.map((table, colIndex) => {
                    if (table === null) {
                        return <View key={colIndex} style={styles.emptyCell} />;
                    }
                    const isSelected = selectedTable === table.name;
                    return (
                        <Pressable
                            key={table.name}
                            style={[
                                styles.tableSquare,
                                isSelected && styles.tableSquareSelected,
                            ]}
                            onPress={() => handleTableSelect(table.name)}
                        >
                            <AppText
                                style={[
                                    styles.tableAbbreviation,
                                    isSelected && styles.tableAbbreviationSelected,
                                ]}
                            >
                                {table.abbreviation}
                            </AppText>
                        </Pressable>
                    );
                })}
            </View>
        ));
    };

    return (
        <AppScreen>
            <ScrollView
                contentContainerStyle={styles.scrollContent}
                showsVerticalScrollIndicator={false}
            >
                {/* Back button */}
                <Pressable style={styles.backButton} onPress={() => router.back()}>
                    <AppText style={styles.backText}>← Back</AppText>
                </Pressable>

                {/* Title */}
                <AppText style={typography.title}>Select Table</AppText>

                {/* Custom Table Input */}
                <View style={styles.inputSection}>
                    <AppText style={styles.label}>Or create a custom table:</AppText>
                    <TextInput
                        style={[
                            styles.input,
                            inputFocused && styles.inputFocused,
                        ]}
                        placeholder="Enter custom table name"
                        placeholderTextColor="#999"
                        value={newTableName}
                        onChangeText={(text) => {
                            setNewTableName(text);
                            if (text) setSelectedTable(null);
                        }}
                        onFocus={() => setInputFocused(true)}
                        onBlur={() => setInputFocused(false)}
                    />
                </View>

                {/* Unified Table Grid */}
                <View style={styles.gridContainer}>
                    {renderGrid()}
                </View>

                {/* Confirm Button */}
                <Pressable
                    onPress={handleConfirm}
                    disabled={isConfirmDisabled}
                    style={({ pressed }) => [
                        styles.confirmButtonWrapper,
                        pressed && !isConfirmDisabled && { transform: [{ scale: 0.98 }] },
                        isConfirmDisabled && { opacity: 0.5 },
                    ]}
                >
                    <LinearGradient colors={gradients.button} style={styles.confirmButton}>
                        <AppText style={styles.confirmButtonText}>
                            Confirm Table
                        </AppText>
                    </LinearGradient>
                </Pressable>
            </ScrollView>
        </AppScreen>
    );
}
