import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Head } from "@inertiajs/react";
import React from "react";
import { useState } from "react";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
    BadgeCheck,
    ChevronLeft,
    ChevronRight,
    ChevronUp,
    Download,
    Edit,
    FileText,
    Key,
    LockKeyhole,
    Plus,
    Search,
    TouchpadOff,
    Upload,
} from "lucide-react";

import Select from "react-select";
import { AddPerusahaanModal } from "@/components/modals/add-perusahaan-modal";
import { EditPerusahaanModal } from "@/components/modals/edit-perusahaan-modal";
import {
    Perusahaan,
    JenisDokIL,
    JenisKegiatan,
    Verifikator,
    Kabupaten,
    Kecamatan,
    Kelurahan,
    Kawasan,
} from "@/types/perusahaan";

export default function PerusahaanIndex({
    perusahaan,
    jenisKegiatan,
    jenisDokIL,
    verifikator,
    kabupaten,
    kecamatan,
    kelurahan,
}: {
    perusahaan: Perusahaan[];
    jenisKegiatan: JenisKegiatan[];
    jenisDokIL: JenisDokIL[];
    verifikator: Verifikator[];
    kabupaten: Kabupaten[];
    kecamatan: Kecamatan[];
    kelurahan: Kelurahan[];
}) {
    console.log("Perusahaan data:", perusahaan);
    // console.log("Jenis Kegiatan data:", jenisKegiatan);
    // console.log("Jenis Dok IL data:", jenisDokIL);
    // console.log("Verifikator data:", verifikator);
    // console.log("Kabupaten data:", kabupaten);
    // console.log("Kecamatan data:", kecamatan);
    // console.log("Kelurahan data:", kelurahan);

    const [year, setYear] = useState<string>("2025");
    const [quarter, setQuarter] = useState<string>("Triwulan 1");

    const [selectedJenisKegiatan, setSelectedJenisKegiatan] = useState<{
        value: string;
        label: string;
    } | null>(null);

    const [selectedJenisDokIL, setSelectedJenisDokIL] = useState<{
        value: string;
        label: string;
    } | null>(null);

    const [selectedVerifikator, setSelectedVerifikator] = useState<{
        value: string;
        label: string;
    } | null>(null);

    const [selectedKabupaten, setSelectedKabupaten] = useState<{
        value: number;
        label: string;
    } | null>(null);

    const [selectedKecamatan, setSelectedKecamatan] = useState<{
        value: number;
        label: string;
    } | null>(null);

    const [selectedKelurahan, setSelectedKelurahan] = useState<{
        value: number;
        label: string;
    } | null>(null);

    const jenisKegiatanOptions = jenisKegiatan.map((jk) => ({
        value: jk.JenisKegiatanId.toString(),
        label: jk.NamaJenisKegiatan,
    }));

    const jenisDokILOptions = jenisDokIL.map((jdi) => ({
        value: jdi.JenisDokILId.toString(),
        label: jdi.NamaJenisDokIL,
    }));

    const verifikatorOptions = verifikator.map((v) => ({
        value: v.VerifikatorId.toString(),
        label: v.NamaUnitKerja,
    }));

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

    const kecamatanOptions = kecamatan
        .filter(
            (kec) =>
                selectedKabupaten && kec.KabupatenId === selectedKabupaten.value
        )
        .map((kec) => ({
            value: kec.KecamatanId,
            label: kec.NamaKecamatan,
        }));

    const kelurahanOptions = kelurahan
        .filter(
            (kel) =>
                selectedKecamatan && kel.KecamatanId === selectedKecamatan.value
        )
        .map((kel) => ({
            value: kel.KelurahanId,
            label: kel.NamaKelurahan,
        }));

    // const companyOptions = [
    //     { value: "PT Ajinomoto Indonesia", label: "PT Ajinomoto Indonesia" },
    //     { value: "PT Unilever Indonesia", label: "PT Unilever Indonesia" },
    //     {
    //         value: "PT Indofood Sukses Makmur",
    //         label: "PT Indofood Sukses Makmur",
    //     },
    //     { value: "PT Mayora Indah", label: "PT Mayora Indah" },
    // ];

    type CompanyOption = {
        value: string;
        label: string;
    };

    const companyOptions: CompanyOption[] = perusahaan.map((c) => ({
        value: c.PerusahaanId.toString(),
        label: c.NamaPerusahaan,
    }));

    const [company, setCompany] = useState<CompanyOption | null>(
        companyOptions[0]
    );
    const [showAddModal, setShowAddModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [selectedPerusahaan, setSelectedPerusahaan] =
        useState<Perusahaan | null>(null);

    const handleSuccess = () => {
        // Refresh data
        window.location.reload();
    };

    const handleEditClick = (item: Perusahaan) => {
        setSelectedPerusahaan(item);
        setShowEditModal(true);
    };

    // Color coding helper
    const getStatusColor = (status: string) => {
        switch (status) {
            case "belum":
                return "bg-red-100 text-red-800";
            case "pending":
                return "bg-gray-100 text-gray-800";
            case "siap":
                return "bg-orange-100 text-orange-800";
            case "selesai":
                return "bg-green-100 text-green-800";
            default:
                return "";
        }
    };
    return (
        <AuthenticatedLayout header={"Daftar Perusahaan"}>
            <Head title="Daftar Perusahaan" />

            <AddPerusahaanModal
                open={showAddModal}
                onClose={() => setShowAddModal(false)}
                onSuccess={handleSuccess}
                jenisKegiatan={jenisKegiatan}
                jenisDokIL={jenisDokIL}
                verifikator={verifikator}
                kabupaten={kabupaten}
                kecamatan={kecamatan}
                kelurahan={kelurahan}
                perusahaan={perusahaan}
            />

            <EditPerusahaanModal
                open={showEditModal}
                onClose={() => setShowEditModal(false)}
                onSuccess={handleSuccess}
                perusahaan={selectedPerusahaan}
                jenisKegiatan={jenisKegiatan}
                jenisDokIL={jenisDokIL}
                verifikator={verifikator}
                kabupaten={kabupaten}
                kecamatan={kecamatan}
                kelurahan={kelurahan}
            />

            {/* Filter Section */}
            <div className="bg-white p-6 rounded-lg shadow-sm mb-6">
                <div className="flex flex-col md:flex-row md:gap-6 py-4">
                    <div className="w-1/2">
                        <h2 className="text-lg font-semibold mb-4 text-gray-800">
                            Filter Pencarian
                        </h2>
                    </div>
                    <div className="w-1/2">
                        <div className="flex md:mt-0 md:justify-end">
                            <Button
                                className="bg-blue-600 hover:bg-blue-950 text-white"
                                onClick={() => setShowAddModal(true)}
                            >
                                <Plus className="w-4 h-4 mr-2" />
                                Tambah Perusahaan
                            </Button>
                        </div>
                    </div>
                </div>
                <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">
                                Perusahaan
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={companyOptions}
                                    value={company}
                                    onChange={setCompany}
                                    placeholder="Pilih Perusahaan"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                />
                            </div>
                        </div>

                        <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
                                    options={kabupatenOptions}
                                    value={selectedKabupaten}
                                    onChange={(value) => {
                                        setSelectedKabupaten(value);
                                        setSelectedKecamatan(null);
                                        setSelectedKelurahan(null);
                                    }}
                                    placeholder="Pilih Kabupaten/Kota"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-3 items-center gap-4">
                            <label className="text-sm font-medium text-gray-700">
                                Kecamatan
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={kecamatanOptions}
                                    value={selectedKecamatan}
                                    onChange={(value) => {
                                        setSelectedKecamatan(value);
                                        setSelectedKelurahan(null);
                                    }}
                                    placeholder="Pilih Kecamatan"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                    isDisabled={!selectedKabupaten}
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-3 items-center gap-4">
                            <label className="text-sm font-medium text-gray-700">
                                Kelurahan
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={kelurahanOptions}
                                    value={selectedKelurahan}
                                    onChange={setSelectedKelurahan}
                                    placeholder="Pilih Kelurahan"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                    isDisabled={!selectedKecamatan}
                                />
                            </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">
                                Jenis Kegiatan
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={jenisKegiatanOptions}
                                    value={selectedJenisKegiatan}
                                    onChange={setSelectedJenisKegiatan}
                                    placeholder="Pilih Jenis Kegiatan"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-3 items-center gap-4">
                            <label className="text-sm font-medium text-gray-700">
                                Admin
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={verifikatorOptions}
                                    value={selectedVerifikator}
                                    onChange={setSelectedVerifikator}
                                    placeholder="Pilih Admin"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                />
                            </div>
                        </div>

                        <div className="grid grid-cols-3 items-center gap-4">
                            <label className="text-sm font-medium text-gray-700">
                                Jenis Izin
                            </label>
                            <div className="col-span-2">
                                <Select
                                    options={jenisDokILOptions}
                                    value={selectedJenisDokIL}
                                    onChange={setSelectedJenisDokIL}
                                    placeholder="Pilih Jenis Izin"
                                    isSearchable
                                    className="w-full"
                                    isClearable
                                />
                            </div>
                        </div>

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

            {/* Table Section */}
            <div className="w-full overflow-x-auto">
                <Table className="min-w-[1000px] border-collapse">
                    <TableHeader>
                        <TableRow className="border-b border-t bg-green-800">
                            <TableHead
                                rowSpan={2}
                                className="w-[50px] border-r border-l text-white"
                            >
                                No.
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Nama Perusahaan
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Jenis Kegiatan
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Alamat
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Kelurahan
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Kecamatan
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Kota
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Kode Pos
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Telp
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Fax
                            </TableHead>
                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Email
                            </TableHead>
                            <TableHead
                                className="border-r text-center text-white"
                                colSpan={2}
                            >
                                Koordinat
                            </TableHead>
                            <TableHead
                                className="border-r text-center text-white"
                                colSpan={2}
                            >
                                Kontak Person
                            </TableHead>
                            <TableHead
                                className="border-r text-center text-white"
                                rowSpan={2}
                            >
                                Admin
                            </TableHead>
                            <TableHead
                                className="border-r text-center text-white"
                                colSpan={4}
                            >
                                Dokumen Izin / Persetujuan Lingkungan Bidang
                                Tata Lingkungan
                            </TableHead>

                            <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Status Laporan
                            </TableHead>
                            {/* <TableHead
                                rowSpan={2}
                                className="border-r text-center text-white"
                            >
                                Aksi
                            </TableHead> */}
                        </TableRow>
                        <TableRow className="border-b bg-green-600">
                            <TableHead className="text-center border-r text-white">
                                Lintang
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Bujur
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Nama
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Telepon
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Nomor
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Tanggal
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Jenis
                            </TableHead>
                            <TableHead className="text-center border-r text-white">
                                Dok
                            </TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody className="border-b">
                        {perusahaan.length === 0 ? (
                            <TableRow>
                                <TableCell
                                    colSpan={21}
                                    className="text-center py-4"
                                >
                                    Tidak ada data perusahaan
                                </TableCell>
                            </TableRow>
                        ) : (
                            perusahaan.map((item, index) => {
                                // Add console log to debug each perusahaan item
                                // console.log(
                                //     "Perusahaan item:",
                                //     item.verifikator
                                // );

                                return (
                                    <TableRow
                                        key={item.PerusahaanId}
                                        className="border-b"
                                    >
                                        <TableCell className="text-center border-r border-l">
                                            {index + 1}
                                        </TableCell>
                                        <TableCell className="border-r">
                                            <div className="flex justify-center">
                                                <Button
                                                    variant="link"
                                                    className="px-2 py-1 bg-green-100 h-auto font-normal justify-center text-center flex items-center gap-1"
                                                    onClick={() =>
                                                        handleEditClick(item)
                                                    }
                                                >
                                                    <Edit className="h-3 w-3 text-green-500" />
                                                    {item.NamaPerusahaan ||
                                                        "N/A"}
                                                </Button>
                                            </div>
                                        </TableCell>

                                        <TableCell className="text-center border-r">
                                            {item.jenis_kegiatan
                                                ?.NamaJenisKegiatan || "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Alamat}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.kelurahan?.NamaKelurahan ||
                                                "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.kelurahan?.kecamatan
                                                ?.NamaKecamatan || "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.kelurahan?.kecamatan
                                                ?.kabupaten?.NamaKabupaten ||
                                                "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.KodePos}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Telepon}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Fax}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Email}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Lintang}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.Bujur}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.CPNama}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.CPTelepon}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.verifikator?.NamaUnitKerja ??
                                                "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.ILNomor || "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.ILTanggal
                                                ? new Date(
                                                      item.ILTanggal
                                                  ).toLocaleDateString("en-GB")
                                                : "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.jenis_dok_i_l
                                                ?.NamaJenisDokIL || "N/A"}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            {item.ILDokumen ? (
                                                <a
                                                    href={`/storage/${item.ILDokumen}`}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    className="flex items-center justify-center"
                                                >
                                                    <FileText className="w-4 h-4 text-green-600 hover:text-green-800" />
                                                </a>
                                            ) : (
                                                <div className="flex items-center justify-center">
                                                    <TouchpadOff className="w-4 h-4" />
                                                </div>
                                            )}
                                        </TableCell>
                                        <TableCell className="text-center border-r">
                                            <div className="flex items-center justify-center">
                                                {item.ReportLocked ? (
                                                    <LockKeyhole className="w-4 h-4 text-red-700" />
                                                ) : (
                                                    <Key className="w-4 h-4 text-green-700" />
                                                )}
                                            </div>
                                        </TableCell>
                                        {/* <TableCell className="text-center border-r">
                                            <Button
                                                variant="outline"
                                                size="icon"
                                                onClick={() =>
                                                    handleEditClick(item)
                                                }
                                            >
                                                <Edit className="h-4 w-4" />
                                            </Button>
                                        </TableCell> */}
                                    </TableRow>
                                );
                            })
                        )}
                    </TableBody>
                </Table>
            </div>
            {/* Pagination */}
            <div className="mt-4 flex items-center gap-2 justify-end">
                <Button variant="outline" size="icon">
                    <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button variant="outline" size="icon">
                    <ChevronRight className="h-4 w-4" />
                </Button>
            </div>
        </AuthenticatedLayout>
    );
}
