import * as React from "react";
import { Checkbox, Text, Button, Divider } from "@fluentui/react-components";
import { SheetInfo } from "../models";
import * as XLSX from "xlsx";

interface SheetSelectorProps {
    sheets: SheetInfo[];
    selectedSheetIds: string[];
    onSelectionChange: (selectedIds: string[]) => void;
    onNext: () => void;
    onExternalSheetsLoaded: (externalSheets: SheetInfo[]) => void;
}

const SheetSelector: React.FC<SheetSelectorProps> = ({
    sheets,
    selectedSheetIds,
    onSelectionChange,
    onNext,
    onExternalSheetsLoaded,
}) => {
    const handleCheckboxChange = (sheetId: string, checked: boolean) => {
        if (checked) {
            onSelectionChange([...selectedSheetIds, sheetId]);
        } else {
            onSelectionChange(selectedSheetIds.filter((id) => id !== sheetId));
        }
    };

    const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const newExternalSheets: SheetInfo[] = [];

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const arrayBuffer = await file.arrayBuffer();

            // Einlesen der Datei mit SheetJS
            const workbook = XLSX.read(arrayBuffer, { type: "array" });

            workbook.SheetNames.forEach((sheetName) => {
                const worksheet = workbook.Sheets[sheetName];
                // Lese Daten als 2D-Array (header: 1 bedeutet Array of Arrays)
                // blankrows: false überspringt komplett leere Zeilen beim Einlesen nicht zwingend, 
                // aber sheet_to_json mit header:1 hält die Struktur relativ gut.
                const data = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: "" }) as any[][];

                // Nur hinzufügen, wenn auch Daten drin sind
                if (data.length > 0) {
                    const uniqueId = `ext_${file.name}_${sheetName}`;
                    newExternalSheets.push({
                        id: uniqueId,
                        name: sheetName,
                        isExternal: true,
                        fileName: file.name,
                        externalData: data
                    });
                }
            });
        }

        // Neue Blätter an die Hauptkomponente übergeben
        if (newExternalSheets.length > 0) {
            onExternalSheetsLoaded(newExternalSheets);
            // Automatisch die neuen Blätter selektieren
            onSelectionChange([...selectedSheetIds, ...newExternalSheets.map(s => s.id)]);
        }
    };

    // Gruppiere Blätter für die Anzeige
    const internalSheets = sheets.filter(s => !s.isExternal);
    const externalSheets = sheets.filter(s => s.isExternal);

    return (
        <div style={{ display: "flex", flexDirection: "column", gap: "10px", padding: "10px" }}>
            <Text size={400} weight="semibold">
                1. Quell-Blätter auswählen
            </Text>
            <Text size={300}>Bitte wähle alle Tabellenblätter aus, die konsolidiert werden sollen:</Text>

            {/* Interne Blätter */}
            <div style={{ marginTop: "10px" }}>
                <Text weight="semibold" style={{ marginBottom: "5px", display: "block" }}>
                    Aus dieser Arbeitsmappe:
                </Text>
                <div style={{ display: "flex", flexDirection: "column", gap: "5px" }}>
                    {internalSheets.length === 0 ? (
                        <Text italic>Keine internen Blätter gefunden.</Text>
                    ) : (
                        internalSheets.map((s) => (
                            <Checkbox
                                key={s.id}
                                label={s.name}
                                checked={selectedSheetIds.includes(s.id)}
                                onChange={(_, data) => handleCheckboxChange(s.id, !!data.checked)}
                            />
                        ))
                    )}
                </div>
            </div>

            <Divider style={{ margin: "10px 0" }} />

            {/* Externe Blätter */}
            <div>
                <Text weight="semibold" style={{ marginBottom: "5px", display: "block" }}>
                    Aus anderen Dateien hinzufügen:
                </Text>
                <input
                    type="file"
                    accept=".xlsx, .xlsm, .xls, .csv"
                    multiple
                    onChange={handleFileUpload}
                    style={{ marginBottom: "10px", display: "block" }}
                />

                {externalSheets.length > 0 && (
                    <div style={{ display: "flex", flexDirection: "column", gap: "5px", marginTop: "10px" }}>
                        {externalSheets.map((s) => (
                            <Checkbox
                                key={s.id}
                                label={`${s.fileName} - ${s.name}`}
                                checked={selectedSheetIds.includes(s.id)}
                                onChange={(_, data) => handleCheckboxChange(s.id, !!data.checked)}
                            />
                        ))}
                    </div>
                )}
            </div>

            <div style={{ marginTop: "20px" }}>
                <Button
                    appearance="primary"
                    disabled={selectedSheetIds.length === 0}
                    onClick={onNext}
                >
                    Weiter zum Mapping
                </Button>
            </div>
        </div>
    );
};

export default SheetSelector;
