"use client";

import * as React from "react";
import { Save } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { DepositReportFiltersForm } from "@/app/customer/[tenant]/reports/deposit-report/_components/deposit-report/deposit-report-filters-form";
import {
  buildDefaultDepositReportFilters,
  depositServerFilterIds,
  type DepositReportFilters,
} from "@/app/customer/[tenant]/reports/deposit-report/_components/deposit-report/schema";
import {
  loadDashboardAssetWidgetSettings,
  updateDashboardAssetWidgetSettings,
} from "../../../_lib/dashboard-widgets-api";
import type { DashboardDepositWidget } from "../../../_lib/dashboard-widgets-server-api";
import type { WidgetConfigPanelProps } from "../types";

function toFilters(
  widget: DashboardDepositWidget | null,
  bankIds: string[],
  currencyIds: string[],
): DepositReportFilters {
  if (!widget) {
    return buildDefaultDepositReportFilters(bankIds, currencyIds);
  }
  return {
    banks: widget.selected_bank_ids.length > 0 ? [...widget.selected_bank_ids] : [...bankIds],
    currencies:
      widget.selected_currency_ids.length > 0
        ? [...widget.selected_currency_ids]
        : [...currencyIds],
  };
}

export function DepositWidgetConfigPanel({
  tenant,
  widget,
  mode = "edit",
  onClose,
  onWidgetsChanged,
}: WidgetConfigPanelProps) {
  const isCreate = mode === "create" || !widget;
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [busy, setBusy] = React.useState(false);
  const [title, setTitle] = React.useState("");
  const [filters, setFilters] = React.useState<DepositReportFilters | null>(null);
  const [bankOptions, setBankOptions] = React.useState<{ id: string; name: string }[]>([]);
  const [currencyOptions, setCurrencyOptions] = React.useState<{ id: string; label: string }[]>(
    [],
  );
  const [currentWidgetId, setCurrentWidgetId] = React.useState<number>(widget?.widget_id ?? 0);

  React.useEffect(() => {
    let cancelled = false;
    void (async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await loadDashboardAssetWidgetSettings(tenant);
        if (cancelled) return;
        const banks = data.banks.map((bank) => ({ id: bank.bank_id, name: bank.bank_name }));
        const bankIds = banks.map((bank) => bank.id);
        const currencies = Object.entries(data.MarketPriceCurrency ?? {}).map(([id, label]) => ({
          id,
          label: String(label),
        }));
        const currencyIds = currencies.map((currency) => currency.id);
        const match =
          !isCreate && widget
            ? (data.deposit_widgets ?? []).find(
                (entry) => Number(entry.widget_id) === Number(widget.widget_id),
              ) ?? null
            : null;
        setBankOptions(banks);
        setCurrencyOptions(currencies);
        setCurrentWidgetId(match?.widget_id ?? widget?.widget_id ?? 0);
        setTitle(match?.title?.trim() || match?.name || widget?.name || "");
        setFilters(toFilters(match, bankIds, currencyIds));
      } catch (loadError) {
        if (!cancelled) {
          setError(
            loadError instanceof Error ? loadError.message : "Deposit settings could not be loaded.",
          );
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [isCreate, tenant, widget]);

  if (loading) return <p className="text-muted-foreground text-sm">Loading configuration…</p>;
  if (error || !filters) {
    return <p className="text-destructive text-sm">{error ?? "Widget settings are unavailable."}</p>;
  }

  const bankIds = bankOptions.map((bank) => bank.id);
  const currencyIds = currencyOptions.map((currency) => currency.id);

  async function save(operation: "deposit-create" | "deposit-save") {
    setBusy(true);
    try {
      const selectedBankIds = depositServerFilterIds(filters!.banks, bankIds);
      const selectedCurrencyIds = depositServerFilterIds(filters!.currencies, currencyIds);
      if (selectedBankIds.length === 0 && bankIds.length > 0 && filters!.banks.length === 0) {
        toast.error("Please select at least one bank.");
        return;
      }
      await updateDashboardAssetWidgetSettings(tenant, {
        operation,
        widgetId: operation === "deposit-create" ? "new" : currentWidgetId,
        title: title.trim(),
        // Full bank selection → send all ids (API requires ≥1). Full currency selection →
        // send [] so the backend treats it as “no currency filter”.
        selectedBankIds: selectedBankIds.length > 0 ? selectedBankIds : bankIds,
        selectedCurrencyIds,
      });
      toast.success(operation === "deposit-create" ? "Deposit widget added" : "Deposit widget saved");
      onWidgetsChanged?.();
      onClose();
    } catch (saveError) {
      toast.error(saveError instanceof Error ? saveError.message : "Deposit widget could not be saved.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="overflow-hidden rounded-lg border bg-card">
      <div className="space-y-2 p-4">
        <Label>{isCreate ? "Widget title (optional)" : "Widget title"}</Label>
        <Input
          value={title}
          placeholder="Deposit"
          onChange={(event) => setTitle(event.target.value)}
        />
      </div>

      <div className="p-4 pt-0">
        <DepositReportFiltersForm
          value={filters}
          onChange={setFilters}
          bankOptionItems={bankOptions}
          currencyOptionItems={currencyOptions}
          variant="settings"
        />
      </div>

      <div className="flex justify-end border-t p-3">
        <Button
          type="button"
          size="sm"
          className="gap-2"
          disabled={busy}
          onClick={() => void save(isCreate ? "deposit-create" : "deposit-save")}
        >
          <Save className="size-4" />
          {busy ? "Saving…" : isCreate ? "Add Widget" : "Save Widget"}
        </Button>
      </div>
    </div>
  );
}
