import DashboardController from "@/actions/App/Http/Controllers/Dashboard/IndexController";
import PageHeader from "@/components/page-header";
import AppLayout from "@/layouts/app-layout";
import { Head, router, usePage } from "@inertiajs/react";
import { useState } from "react";
import { Card, Col, Container, Row, Table, Form } from "react-bootstrap";
import {
    PiUser,
    PiUsersThree,
    PiClockAfternoon,
    PiClockClockwise,
    PiWarningCircle,
    PiCheckCircle,
    PiMonitor,
} from "react-icons/pi";
import * as Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";

import Exporting from "highcharts/modules/exporting";
import { SharedData } from "@/types";
import useReactSelectTheme from "@/hooks/use-react-select";
import Select from "react-select";

interface PageProps {
    title: string;
    filters: { month: string; year: string; skpd_id?: string };
    skpds: { skpd_id: number; name: string }[];
    resource: {
        masuk: number;
        terlambat: number;
        pulang: number;
        pulang_cepat: number;
        total_pegawai: number;
        belum_konfirmasi: number;
        pegawai_izin: number;
    };
}

export default function Dashboard({
    title,
    filters,
    skpds,
    resource,
}: PageProps) {
    const theme = useReactSelectTheme();
    const { auth } = usePage<SharedData>().props;
    const [filterData, setFilterData] = useState({
        month: filters.month,
        year: filters.year,
        skpd_id: filters.skpd_id || "",
    });
    const skpdOptions = [
        { value: "", label: "Semua SKPD" },
        ...skpds.map((s) => ({
            value: s.skpd_id,
            label: s.name,
        })),
    ];
    // List pilihan bulan
    const months = [
        { v: "01", n: "Januari" },
        { v: "02", n: "Februari" },
        { v: "03", n: "Maret" },
        { v: "04", n: "April" },
        { v: "05", n: "Mei" },
        { v: "06", n: "Juni" },
        { v: "07", n: "Juli" },
        { v: "08", n: "Agustus" },
        { v: "09", n: "September" },
        { v: "10", n: "Oktober" },
        { v: "11", n: "November" },
        { v: "12", n: "Desember" },
    ];

    const selectedMonth = months.find((m) => m.v === filters.month);
    const monthName = selectedMonth ? selectedMonth.n : filters.month;

    // List pilihan tahun (5 tahun terakhir)
    const years = Array.from({ length: 5 }, (_, i) =>
        (new Date().getFullYear() - i).toString(),
    );

    const handleFilter = () => {
        router.get(route("dashboard"), filterData, {
            preserveState: true,
            replace: true,
        });
    };
    if (typeof Highcharts === "object") {
        // Di beberapa versi Highcharts, Exporting diimpor sebagai objek yang memiliki default function
        const isFunction = typeof Exporting === "function";
        if (isFunction) {
            (Exporting as any)(Highcharts);
        } else {
            (Exporting as any).default?.(Highcharts);
        }
    }
    const chartOptions: Highcharts.Options = {
        chart: {
            type: "pie",
            backgroundColor: "transparent",
        },
        title: {
            text: `Grafik Jumlah Data Absensi: ${monthName} ${filters.year}`,
            style: { fontSize: "18px", fontWeight: "bold" },
        },
        exporting: {
            enabled: true,
            buttons: {
                contextButton: {
                    menuItems: [
                        "viewFullscreen",
                        "printChart",
                        "separator",
                        "downloadPNG",
                        "downloadJPEG",
                        "downloadPDF",
                        "downloadSVG",
                    ],
                },
            },
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: "pointer",
                dataLabels: {
                    enabled: true,
                    format: "<b>{point.name}</b>: {point.percentage:.1f}%",
                    connectorColor: "silver",
                    distance: 30,
                },
                showInLegend: true,
            },
        },
        colors: [
            "#7cb5ec",
            "#434348",
            "#90ed7d",
            "#f7a35c",
            "#8085e9",
            "#f15c80",
            "#e4d354",
        ],
        // PERBAIKAN DI SINI: Gunakan 'as any' jika tipe data masih bentrok,
        // atau definisikan secara eksplisit
        series: [
            {
                type: "pie",
                name: "Persentase",
                colorByPoint: true,
                data: [
                    { name: "Masuk", y: resource.masuk },
                    { name: "Terlambat", y: resource.terlambat },
                    { name: "Pulang", y: resource.pulang },
                    { name: "Pulang Cepat", y: resource.pulang_cepat },
                    { name: "Jumlah Pegawai", y: resource.total_pegawai },
                    { name: "Belum Konfirmasi", y: resource.belum_konfirmasi },
                    { name: "Ijin", y: resource.pegawai_izin },
                ],
            },
        ] as any, // Menggunakan 'as any' di sini adalah cara tercepat menghilangkan error 'colorByPoint' di TS
        legend: {
            align: "center",
            verticalAlign: "bottom",
            layout: "horizontal",
        },
        credits: { enabled: false },
    };

    return (
        <AppLayout>
            <Head title={title} />

            <Container fluid className="p-0">
                <PageHeader title={title} />
                {auth.user.role !== "atasan" && (
                    <>
                        {/* Filter Section (Hanya Bulan & Tahun) */}
                        <Card className="mb-4 border-0 shadow-sm">
                            <Card.Body>
                                <Row className="g-2 align-items-end">
                                    <Col
                                        md={auth.user.role === "admin" ? 3 : 4}
                                    >
                                        <Form.Label className="small fw-bold">
                                            Pilih Bulan
                                        </Form.Label>
                                        <Form.Select
                                            value={filterData.month}
                                            onChange={(e) =>
                                                setFilterData({
                                                    ...filterData,
                                                    month: e.target.value,
                                                })
                                            }
                                        >
                                            {months.map((m) => (
                                                <option key={m.v} value={m.v}>
                                                    {m.n}
                                                </option>
                                            ))}
                                        </Form.Select>
                                    </Col>
                                    <Col
                                        md={auth.user.role === "admin" ? 3 : 4}
                                    >
                                        <Form.Label className="small fw-bold">
                                            Pilih Tahun
                                        </Form.Label>
                                        <Form.Select
                                            value={filterData.year}
                                            onChange={(e) =>
                                                setFilterData({
                                                    ...filterData,
                                                    year: e.target.value,
                                                })
                                            }
                                        >
                                            {years.map((y) => (
                                                <option key={y} value={y}>
                                                    {y}
                                                </option>
                                            ))}
                                        </Form.Select>
                                    </Col>

                                    {/* Tampilkan filter SKPD hanya untuk role Admin */}
                                    {auth.user.role === "admin" && (
                                        <Col md={3}>
                                            <Form.Label className="small fw-bold">
                                                Unit Kerja (SKPD)
                                            </Form.Label>
                                            <Select
                                                options={skpdOptions}
                                                value={skpdOptions.find(
                                                    (opt: any) =>
                                                        opt.value ===
                                                        filterData.skpd_id,
                                                )}
                                                onChange={(opt: any) =>
                                                    setFilterData({
                                                        ...filterData,
                                                        skpd_id: opt.value,
                                                    })
                                                }
                                                placeholder="Pilih SKPD..."
                                                isClearable
                                                styles={theme}
                                            />
                                        </Col>
                                    )}

                                    <Col
                                        md={auth.user.role === "admin" ? 3 : 4}
                                    >
                                        <div className="d-flex gap-2">
                                            <button
                                                onClick={handleFilter}
                                                className="btn btn-primary px-4"
                                            >
                                                Filter
                                            </button>
                                            <button
                                                onClick={() =>
                                                    (window.location.href =
                                                        DashboardController.index.url())
                                                }
                                                className="btn btn-warning text-white px-4"
                                            >
                                                Refresh
                                            </button>
                                        </div>
                                    </Col>
                                </Row>
                            </Card.Body>
                        </Card>

                        {/* Info Header Dashboard */}
                        <div className="text-center mb-4">
                            <h5 className="fw-bold mb-0 text-uppercase">
                                Dashboard E-Presensi PPPK Paruh Waktu{" "}
                                {auth.user.role === "pegawai"
                                    ? "Pegawai"
                                    : "Kota Kediri"}
                            </h5>
                            <p className="text-muted small">
                                {auth.user.role === "pegawai" && auth.user.name}
                                {auth.user.role === "admin-opd" &&
                                    auth.user.skpdKode?.name}
                                {auth.user.role === "admin" &&
                                    (skpds.find(
                                        (s) =>
                                            String(s.skpd_id) ===
                                            String(filters.skpd_id),
                                    )?.name ||
                                        "Semua SKPD")}
                                <br />
                                Periode:{" "}
                                {
                                    months.find((m) => m.v === filters.month)?.n
                                }{" "}
                                {filters.year}
                            </p>
                        </div>

                        {/* 1. Baris Kotak Statistik (Counters) */}
                        <Row className="g-3 mb-4">
                            {/* Baris Pertama */}
                            <Col md={4}>
                                <StatCard
                                    title="Masuk"
                                    value={resource.masuk}
                                    color="#20c997"
                                    icon={
                                        <PiCheckCircle
                                            size={40}
                                            opacity={0.2}
                                        />
                                    }
                                />
                            </Col>
                            <Col md={4}>
                                <StatCard
                                    title="Pulang"
                                    value={resource.pulang}
                                    color="#0d6efd"
                                    icon={
                                        <PiClockAfternoon
                                            size={40}
                                            opacity={0.2}
                                        />
                                    }
                                />
                            </Col>
                            <Col md={4}>
                                <StatCard
                                    title="Jumlah Pegawai"
                                    value={resource.total_pegawai}
                                    color="#a3cfbb"
                                    icon={
                                        <PiUsersThree size={40} opacity={0.2} />
                                    }
                                />
                            </Col>

                            {/* Baris Kedua */}
                            <Col md={4}>
                                <StatCard
                                    title="Jumlah Keterlambatan"
                                    value={resource.terlambat}
                                    color="#dc3545"
                                    icon={
                                        <PiWarningCircle
                                            size={40}
                                            opacity={0.2}
                                        />
                                    }
                                />
                            </Col>
                            <Col md={4}>
                                <StatCard
                                    title="Jumlah Pulang Lebih Awal"
                                    value={resource.pulang_cepat}
                                    color="#f87171"
                                    icon={
                                        <PiClockClockwise
                                            size={40}
                                            opacity={0.2}
                                        />
                                    }
                                />
                            </Col>
                            <Col md={4}>
                                <StatCard
                                    title="Jumlah Belum Konfirmasi"
                                    value={resource.belum_konfirmasi}
                                    color="#ef4444"
                                    icon={
                                        <PiWarningCircle
                                            size={40}
                                            opacity={0.2}
                                        />
                                    }
                                />
                            </Col>

                            {/* Baris Ketiga */}
                            <Col md={4}>
                                <StatCard
                                    title="Jumlah Pegawai Ijin"
                                    value={resource.pegawai_izin}
                                    color="#2dd4bf"
                                    icon={<PiUser size={40} opacity={0.2} />}
                                />
                            </Col>
                        </Row>

                        {/* 2. Bagian Chart */}
                        <Card
                            className="mb-4 border-0 shadow-sm"
                            style={{
                                background:
                                    "linear-gradient(to bottom, #f0f4ff, #ffffff)",
                            }}
                        >
                            <Card.Body>
                                <div className="position-relative">
                                    {/* Tombol menu hamburger kecil di pojok kanan chart */}
                                    <div className="position-absolute top-0 end-0 p-2">
                                        <button className="btn btn-light btn-sm">
                                            <span className="navbar-toggler-icon"></span>
                                        </button>
                                    </div>
                                    <HighchartsReact
                                        highcharts={Highcharts}
                                        options={chartOptions}
                                    />
                                </div>
                            </Card.Body>
                        </Card>
                    </>
                )}
            </Container>
        </AppLayout>
    );
}

// Komponen Reusable untuk Kartu Statistik
function StatCard({
    title,
    value,
    color,
    icon,
}: {
    title: string;
    value: number;
    color: string;
    icon: React.ReactNode;
}) {
    return (
        <Card
            className="border-0 text-white h-100"
            style={{ backgroundColor: color }}
        >
            <Card.Body className="d-flex justify-content-between align-items-center">
                <div>
                    <h2 className="fw-bold mb-0">{value}</h2>
                    <small
                        className="text-uppercase fw-semibold"
                        style={{ fontSize: "0.7rem" }}
                    >
                        {title}
                    </small>
                </div>
                {icon}
            </Card.Body>
        </Card>
    );
}
