"use client";

import { useState } from "react";
import type { PaymentMethodReportParams } from "@/lib/api/reports-payment-methods";
import { getErrorMessage } from "@/lib/api/types";
import { toOwnerDateParam } from "@/lib/dashboard/owner-dashboard";
import {
  formatLaporanDateRangeLabel,
  getDefaultLaporanDateRange,
  getPaymentMethodFilterLabel,
} from "@/lib/laporan/metode-pembayaran";
import { useLaporanBranchFilter } from "@/lib/hooks/use-laporan-branch-filter";
import { usePaymentMethods } from "@/lib/query/hooks/payment-methods";
import { usePaymentMethodReport } from "@/lib/query/hooks/reports-payment-methods";
import { OwnerDateRangePicker } from "../owner/owner-date-range-picker";
import { Button } from "../ui/button";
import { FormMultiSearchSelect } from "../ui/form-multi-search-select";
import { FormSearchSelect } from "../ui/form-search-select";
import { LaporanMetodePembayaranTable } from "./laporan-metode-pembayaran-table";

export function LaporanMetodePembayaranView() {
  const paymentMethodsQuery = usePaymentMethods();
  const paymentMethods = paymentMethodsQuery.data ?? [];
  const {
    branchesQuery,
    branchOptions,
    effectiveBranchId,
    branchIdParam,
    handleBranchChange,
  } = useLaporanBranchFilter();

  const methodOptions = paymentMethods.map((item) => ({
    value: String(item.id),
    label: getPaymentMethodFilterLabel(item.type, item.bank),
  }));

  const [dateRange, setDateRange] = useState(() => getDefaultLaporanDateRange());
  const [selectedMethodIds, setSelectedMethodIds] = useState<string[]>([]);
  const [appliedParams, setAppliedParams] =
    useState<PaymentMethodReportParams | null>(null);

  const reportQuery = usePaymentMethodReport(appliedParams);

  const dateRangeLabel = formatLaporanDateRangeLabel(
    dateRange.start,
    dateRange.end,
  );

  const error =
    (branchesQuery.error
      ? getErrorMessage(branchesQuery.error, "Gagal memuat data cabang.")
      : null) ??
    (paymentMethodsQuery.error
      ? getErrorMessage(
          paymentMethodsQuery.error,
          "Gagal memuat metode pembayaran.",
        )
      : null) ??
    (reportQuery.error
      ? getErrorMessage(
          reportQuery.error,
          "Gagal memuat laporan metode pembayaran.",
        )
      : null);

  function handleSearch() {
    const paymentMethodIds = selectedMethodIds
      .map((id) => Number(id))
      .filter((id) => Number.isFinite(id));

    const nextParams: PaymentMethodReportParams = {
      dateFrom: toOwnerDateParam(dateRange.start),
      dateTo: toOwnerDateParam(dateRange.end),
      ...(branchIdParam != null ? { branchId: branchIdParam } : {}),
      ...(paymentMethodIds.length > 0 ? { paymentMethodIds } : {}),
    };

    const isSameFilter =
      appliedParams != null &&
      JSON.stringify(appliedParams) === JSON.stringify(nextParams);

    setAppliedParams(nextParams);

    if (isSameFilter) {
      void reportQuery.refetch();
    }
  }

  const showReportLoading =
    appliedParams != null &&
    (reportQuery.isPending || reportQuery.isFetching) &&
    !reportQuery.data;

  return (
    <div className="flex min-h-[calc(100vh-114px)] min-w-0 flex-col gap-5">
      {error && (
        <p className="text-m-regular rounded-lg border border-danger-200 bg-danger-50 px-4 py-3 text-danger-700">
          {error}
        </p>
      )}

      <section className="min-w-0 rounded-[10px] border border-neutral-40 bg-neutral-10">
        <div className="relative flex items-center gap-2 px-5 pt-5">
          <div className="absolute top-5 left-0 h-5 w-1 rounded-r-sm bg-primary-500" />
          <h1 className="text-l-medium text-neutral-100">Metode Pembayaran</h1>
        </div>

        <div className="flex flex-col gap-4 p-5">
          <div className="flex flex-col gap-2">
            <p className="text-m-medium text-neutral-100">Tanggal Transaksi</p>
            <OwnerDateRangePicker
              value={dateRange}
              label={dateRangeLabel}
              onChange={setDateRange}
              variant="field"
            />
          </div>

          <FormSearchSelect
            id="laporan-pembayaran-cabang"
            label="Cabang"
            value={effectiveBranchId}
            placeholder={
              branchesQuery.isPending ? "Memuat cabang..." : "Semua Cabang"
            }
            searchPlaceholder="Cari cabang..."
            disabled={branchesQuery.isPending}
            options={branchOptions}
            onChange={handleBranchChange}
          />

          <FormMultiSearchSelect
            id="laporan-pembayaran"
            label="Pembayaran"
            values={selectedMethodIds}
            options={methodOptions}
            onChange={setSelectedMethodIds}
            placeholder={
              paymentMethodsQuery.isPending
                ? "Memuat metode pembayaran..."
                : "Pilih metode pembayaran"
            }
            searchPlaceholder="Cari pembayaran..."
            disabled={
              paymentMethodsQuery.isPending || methodOptions.length === 0
            }
          />

          <Button
            type="button"
            variant="primary"
            size="md"
            className="w-full"
            onClick={handleSearch}
            disabled={
              branchesQuery.isPending ||
              paymentMethodsQuery.isPending ||
              (reportQuery.isFetching && appliedParams != null)
            }
          >
            {reportQuery.isFetching && appliedParams != null
              ? "Memuat..."
              : "Cari"}
          </Button>
        </div>
      </section>

      <section className="min-w-0 rounded-[10px] border border-neutral-40 bg-neutral-10">
        <div className="relative flex items-center gap-2 border-b border-neutral-40 px-5 py-4">
          <div className="absolute top-1/2 left-0 h-5 w-1 -translate-y-1/2 rounded-r-sm bg-primary-500" />
          <h2 className="text-l-medium pl-3 text-neutral-100">
            Laporan Metode Pembayaran
          </h2>
        </div>

        <div className="p-5">
          <LaporanMetodePembayaranTable
            result={appliedParams ? (reportQuery.data ?? null) : null}
            isLoading={showReportLoading}
          />
        </div>
      </section>
    </div>
  );
}
