import { Input } from "@/components/ui/input";
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import {
    HistoryKegiatan,
    JenisKegiatan,
    Kabupaten,
    Perusahaan,
} from "@/types/perusahaan";
import { Head } from "@inertiajs/react";
import { Search } from "lucide-react";
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { HistoryPerusahaanTable } from "@/components/HistoryPerusahaan/TableHistory";
import Select from "react-select"; // Import React-Select
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

type HistoryPerusahaanIndexProps = {
    perusahaan?: Perusahaan[];
    historyKegiatan?: HistoryKegiatan[];
    kabupaten?: Kabupaten[];
};

export default function HistoryPerusahaanIndex({
    perusahaan = [], // Default to empty array
    historyKegiatan = [], // Default to empty array
    kabupaten = [], // Default to empty array
}: HistoryPerusahaanIndexProps) {
    // Define more precise types for select options
    type SelectOption = {
        value: string;
        label: string;
        kabupatenId?: string;
        kabupatenName?: string;
    };

    // Define options first before using them
    const historyKegiatanOptions: SelectOption[] = historyKegiatan.map(
        (jk) => ({
            value: jk.HistoryKegiatanId.toString(),
            label: jk.NamaHistoryKegiatan,
        })
    );

    const kabupatenOptions: SelectOption[] = kabupaten.map((k) => ({
        value: k.KabupatenId.toString(),
        label: k.NamaKabupaten,
    }));

    const companyOptions: SelectOption[] = perusahaan.map((c) => {
        const kabupatenName =
            c.kelurahan?.kecamatan?.kabupaten?.NamaKabupaten || "Unknown";
        return {
            value: c.PerusahaanId.toString(),
            label: c.NamaPerusahaan,
            kabupatenId:
                c.kelurahan?.kecamatan?.kabupaten?.KabupatenId?.toString(),
            kabupatenName: kabupatenName,
        };
    });

    // State management with more explicit typing
    const [selectedHistoryKegiatan, setSelectedHistoryKegiatan] =
        useState<SelectOption | null>(null);
    const [selectedKabupaten, setSelectedKabupaten] =
        useState<SelectOption | null>(null);
    const [company, setCompany] = useState<SelectOption | null>(
        companyOptions.length > 0 ? companyOptions[0] : null
    );

    // Now initialize filteredCompanies after companyOptions is defined
    const [filteredCompanies, setFilteredCompanies] = useState(companyOptions);

    // Add state for number search
    const [nomorPerusahaan, setNomorPerusahaan] = useState<string>("");

    // Add state for filtered perusahaan data
    const [filteredPerusahaan, setFilteredPerusahaan] =
        useState<Perusahaan[]>(perusahaan);

    // Update filtered companies when kabupaten selection changes
    useEffect(() => {
        if (selectedKabupaten) {
            const filtered = companyOptions.filter(
                (option) => option.kabupatenId === selectedKabupaten.value
            );
            setFilteredCompanies(filtered);
        } else {
            setFilteredCompanies(companyOptions);
        }
    }, [selectedKabupaten]);

    // Explicit typing for onChange handlers
    const handleCompanyChange = (selectedOption: SelectOption | null) => {
        setCompany(selectedOption);
    };

    const handleNomorPerusahaanChange = (
        e: React.ChangeEvent<HTMLInputElement>
    ) => {
        setNomorPerusahaan(e.target.value);
    };

    // Search function
    const handleSearch = () => {
        // Start with all perusahaan data
        let results = [...perusahaan];

        // Filter by nomor perusahaan if provided
        if (nomorPerusahaan.trim() !== "") {
            results = results.filter((p) =>
                p.NomorInduk?.toLowerCase().includes(
                    nomorPerusahaan.toLowerCase()
                )
            );
        }

        // Filter by selected company if provided
        if (company) {
            results = results.filter(
                (p) => p.PerusahaanId.toString() === company.value
            );
        }

        // Filter by selected kabupaten if provided
        if (selectedKabupaten) {
            results = results.filter((p) => {
                // Handle potential null/undefined values safely
                const kabupatenId =
                    p.kelurahan?.kecamatan?.kabupaten?.KabupatenId;
                return kabupatenId
                    ? kabupatenId.toString() === selectedKabupaten.value
                    : false;
            });
        }

        // Filter by selected history kegiatan if provided
        if (selectedHistoryKegiatan) {
            results = results.filter((p) => {
                // Check if historyKegiatan exists and is an array
                const historyKegiatanArray = p.historyKegiatan;
                if (
                    !historyKegiatanArray ||
                    !Array.isArray(historyKegiatanArray)
                ) {
                    return false;
                }

                // Check if any historyKegiatan matches the selected one
                return historyKegiatanArray.some((hk) => {
                    return (
                        hk &&
                        hk.HistoryKegiatanId &&
                        hk.HistoryKegiatanId.toString() ===
                            selectedHistoryKegiatan.value
                    );
                });
            });
        }

        // Update the filtered results
        setFilteredPerusahaan(results);
    };

    // Custom styles for React-Select
    const selectStyles = {
        control: (base: any) => ({
            ...base,
            minHeight: "38px",
            borderRadius: "0.375rem",
            borderColor: "#e2e8f0",
            boxShadow: "none",
            "&:hover": {
                borderColor: "#cbd5e0",
            },
        }),
    };

    return (
        <AuthenticatedLayout header={"History Perusahaan"}>
            <Head title="History Perusahaan" />
            <div className="container mx-auto p-4">
                {/* Filter Section */}
                <div className="bg-white py-6 rounded-lg shadow-sm mb-6">
                    <Card className="shadow-md border-slate-200">
                        <CardHeader className="pb-3">
                            <CardTitle className="text-lg font-medium">
                                Filter Pencarian
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                {/* Left Column */}
                                <div className="space-y-4">
                                    <div className="grid grid-cols-3 items-center gap-4">
                                        <label className="text-sm font-medium text-gray-700">
                                            Nomor Perusahaan
                                        </label>
                                        <div className="col-span-2">
                                            <Input
                                                placeholder="Masukkan Nomor Perusahaan"
                                                className="w-full"
                                                value={nomorPerusahaan}
                                                onChange={
                                                    handleNomorPerusahaanChange
                                                }
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-3 items-center gap-4">
                                        <label className="text-sm font-medium text-gray-700">
                                            Perusahaan
                                        </label>
                                        <div className="col-span-2">
                                            <Select
                                                className="basic-single"
                                                classNamePrefix="select"
                                                value={company}
                                                onChange={handleCompanyChange}
                                                options={filteredCompanies}
                                                isClearable={true}
                                                isSearchable={true}
                                                placeholder="Pilih Perusahaan"
                                                noOptionsMessage={() =>
                                                    "Tidak ada data"
                                                }
                                                styles={selectStyles}
                                            />
                                        </div>
                                    </div>
                                </div>

                                {/* Right Column */}
                                <div className="space-y-4">
                                    <div className="grid grid-cols-3 items-center gap-4">
                                        <label className="text-sm font-medium text-gray-700">
                                            Kabupaten/Kota
                                        </label>
                                        <div className="col-span-2">
                                            <Select
                                                className="basic-single"
                                                classNamePrefix="select"
                                                value={selectedKabupaten}
                                                onChange={setSelectedKabupaten}
                                                options={kabupatenOptions}
                                                isClearable={true}
                                                isSearchable={true}
                                                placeholder="Pilih Kabupaten/Kota"
                                                noOptionsMessage={() =>
                                                    "Tidak ada data"
                                                }
                                                styles={selectStyles}
                                            />
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-3 items-center gap-4">
                                        <label className="text-sm font-medium text-gray-700">
                                            Kelompok Kegiatan
                                        </label>
                                        <div className="col-span-2">
                                            <Select
                                                className="basic-single"
                                                classNamePrefix="select"
                                                value={selectedHistoryKegiatan}
                                                onChange={
                                                    setSelectedHistoryKegiatan
                                                }
                                                options={historyKegiatanOptions}
                                                isClearable={true}
                                                isSearchable={true}
                                                placeholder="Pilih Kelompok Kegiatan"
                                                noOptionsMessage={() =>
                                                    "Tidak ada data"
                                                }
                                                styles={selectStyles}
                                            />
                                        </div>
                                    </div>

                                    <div className="flex justify-end mt-6">
                                        <Button
                                            className="bg-green-600 hover:bg-green-700 text-white"
                                            onClick={handleSearch}
                                        >
                                            <Search className="w-4 h-4 mr-2" />
                                            Cari
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Table Section - Now uses filteredPerusahaan */}
                <HistoryPerusahaanTable data={filteredPerusahaan} />
            </div>
        </AuthenticatedLayout>
    );
}
