"use client";

import { CheckCircle2, Loader2, Plus, Wallet, X } from "lucide-react";

import { ErrorBanner } from "@/components/shared/error-banner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import {
  Popover,
  PopoverContent,
  PopoverHeader,
  PopoverTitle,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";

import { formatAmountInput } from "./cash-balance-validation";
import { CashBalanceEmptyState, CashBalanceLoadingState } from "./cash-balance-editor-ui";
import { useCashBalanceEditor, type CashBalanceEditorProps } from "./use-cash-balance-editor";

export function CashBalanceEditor(props: CashBalanceEditorProps) {
  const {
    banks,
    reportingCurrencies,
    selectedBankId,
    bankForm,
    currencyRows,
    setCurrencyRows,
    availableCurrencies,
    selectedAddCurrencyId,
    setSelectedAddCurrencyId,
    lastUpdated,
    showAddBankMenu,
    setShowAddBankMenu,
    newBankName,
    setNewBankName,
    newBankCurrencyId,
    setNewBankCurrencyId,
    addBankError,
    isLoading,
    isFormLoading,
    isSaving,
    isCreatingBank,
    showSavedMessage,
    errorMessage,
    handleSave,
    handleBankChange,
    handleAddCurrency,
    handleRemoveCurrency,
    handleCreateBank,
    handleCancel,
    selectedBankName,
    showFormFooter,
    lockedBankId,
    corporateView,
  } = useCashBalanceEditor(props);

  const hidePageChrome = props.hidePageChrome ?? false;

  if (isLoading) {
    return (
      <div className="flex min-h-full w-full flex-1 flex-col bg-muted/20">
        <div className="px-4 py-10 lg:px-6">
          <CashBalanceLoadingState label="Loading cash balance editor…" />
        </div>
      </div>
    );

  }

  if (errorMessage) {
    return (
      <div className="flex min-h-full w-full flex-1 flex-col bg-muted/20">
        <div className="px-4 py-6 lg:px-6">
          <ErrorBanner message={errorMessage} />
        </div>
      </div>
    );

  }

  return (
    <div className={hidePageChrome ? "flex w-full min-w-0 flex-col gap-6" : "flex min-h-full w-full min-w-0 flex-1 flex-col bg-muted/20"}>
      <div
        className={
          hidePageChrome
            ? "flex w-full min-w-0 flex-col gap-6"
            : corporateView
              ? "flex w-full min-w-0 flex-1 flex-col gap-6 px-4 pt-6 pb-10 lg:gap-8 lg:px-6 lg:pt-8"
              : "flex w-full min-w-0 flex-1 flex-col gap-6 px-4 pt-6 pb-24 lg:gap-8 lg:px-6 lg:pt-8"
        }
      >
        {!hidePageChrome ? (
        <header className="flex w-full min-w-0 flex-col gap-4 border-b border-border/60 pb-5 sm:flex-row sm:items-start sm:justify-between">
          <div className="flex min-w-0 items-start gap-4">
            <div className="flex size-11 shrink-0 items-center justify-center rounded-xl border border-primary/20 bg-primary/10 text-primary shadow-xs">
              <Wallet className="size-5" />
            </div>
            <div className="min-w-0">
              <div className="flex flex-wrap items-center gap-2">
                <h1 className="font-semibold text-2xl tracking-tight text-foreground">
                  {corporateView ? "List Cash Balance" : "Update Cash Balance"}
                </h1>
                <Badge variant="outline" className="font-normal">
                  FX &amp; Currency
                </Badge>
              </div>
              <p className="mt-1 text-muted-foreground text-sm leading-relaxed">
                {corporateView
                  ? "Select a bank to view cash balances across currencies."
                  : "Manage per-bank cash balances across your reporting currencies."}
              </p>
            </div>
          </div>
        </header>
        ) : null}

        {!lockedBankId ? (
        <section className="overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm">
          <div className="border-b border-border/50 bg-muted/25 px-5 py-4 sm:px-6">
            <p className="font-semibold text-base tracking-tight">Bank account</p>
            <p className="mt-0.5 text-muted-foreground text-sm">
              {corporateView
                ? "Select a bank to view its currency balances."
                : "Select a bank or add a new one to edit balances."}
            </p>
          </div>

          <div className="space-y-4 px-5 py-5 sm:px-6">
            <div className="grid w-full max-w-2xl gap-2">
              <Label htmlFor="cash-balance-bank">
                Bank <span className="text-destructive">*</span>
              </Label>

              <div className="flex items-start gap-2">
                <NativeSelect
                  id="cash-balance-bank"
                  value={selectedBankId}
                  onChange={(event) => void handleBankChange(event.target.value)}
                  className="min-w-0 flex-1"
                >
                  <NativeSelectOption value="">Please Select</NativeSelectOption>
                  {banks.map((bank) => (
                    <NativeSelectOption key={`bank-${bank.id}`} value={bank.id}>
                      {bank.name}
                    </NativeSelectOption>
                  ))}
                </NativeSelect>

                {!corporateView ? (
                  <Popover open={showAddBankMenu} onOpenChange={setShowAddBankMenu}>
                    <PopoverTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        size="icon"
                        aria-label="Add bank"
                        className="shrink-0"
                      >
                        <Plus className="size-4" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent
                      align="end"
                      side="bottom"
                      sideOffset={8}
                      className="w-80 gap-0 p-4"
                      onOpenAutoFocus={(event) => event.preventDefault()}
                    >
                      <PopoverHeader className="mb-3 gap-0">
                        <PopoverTitle className="text-sm">Add new bank</PopoverTitle>
                      </PopoverHeader>
                      <div className="space-y-3">
                        <div className="grid gap-2">
                          <Label htmlFor="r_currency">Reporting currency</Label>
                          <NativeSelect
                            id="r_currency"
                            value={newBankCurrencyId}
                            onChange={(event) => setNewBankCurrencyId(event.target.value)}
                            className="w-full"
                          >
                            <NativeSelectOption value="">Please Select</NativeSelectOption>
                            {reportingCurrencies.map((currency) => (
                              <NativeSelectOption key={currency.currency_id} value={String(currency.currency_id)}>
                                {currency.label}
                              </NativeSelectOption>
                            ))}
                          </NativeSelect>
                        </div>

                        <div className="grid gap-2">
                          <Label htmlFor="bnk">Bank name</Label>
                          <div className="flex gap-2">
                            <Input
                              id="bnk"
                              type="text"
                              placeholder="Enter bank name"
                              value={newBankName}
                              onChange={(event) => setNewBankName(event.target.value)}
                              onKeyDown={(event) => {
                                if (event.key === "Enter") {
                                  event.preventDefault();
                                  void handleCreateBank();
                                }
                              }}
                              className="h-8"
                            />
                            <Button
                              type="button"
                              size="sm"
                              disabled={isCreatingBank}
                              onClick={() => void handleCreateBank()}
                              className="shrink-0"
                            >
                              {isCreatingBank ? (
                                <>
                                  <Loader2 className="size-3.5 animate-spin" />
                                  Saving
                                </>
                              ) : (
                                "Save"
                              )}
                            </Button>
                          </div>
                        </div>

                        {addBankError ? <p className="text-destructive text-sm">{addBankError}</p> : null}
                      </div>
                    </PopoverContent>
                  </Popover>
                ) : null}
              </div>
            </div>
          </div>
        </section>
        ) : null}

        <section id="content-loader" className="min-w-0">
          {!selectedBankId ? (
            <CashBalanceEmptyState
              title="Select a bank"
              description={
                corporateView
                  ? "Choose a bank account above to view cash balances."
                  : "Choose a bank account above to view and edit cash balances."
              }
            />
          ) : isFormLoading ? (
            <CashBalanceLoadingState label="Loading currencies…" />
          ) : bankForm ? (
            <div className="the-cashfrm overflow-hidden rounded-xl border border-border/60 bg-card shadow-sm">
              <div className="border-b border-border/50 bg-muted/25 px-5 py-4 sm:px-6">
                <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <p className="font-semibold text-base tracking-tight">
                      Cash balances for <span className="text-primary">{selectedBankName}</span>
                    </p>
                    <p className="mt-0.5 text-muted-foreground text-sm">
                      {corporateView
                        ? "Currency balances for the selected bank."
                        : "Enter amounts for each currency. Leave blank to exclude from save."}
                    </p>
                  </div>
                  <div className="text-muted-foreground text-sm">
                    <span className="font-medium text-foreground">Last updated</span>{" "}
                    <span className="date font-mono tabular-nums">{lastUpdated ?? "—"}</span>
                  </div>
                </div>
              </div>

              <div className="space-y-6 px-5 py-5 sm:px-6">
                <div
                  className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
                  id="appendor"
                >
                  {currencyRows.map((row) => (
                    <div
                      key={row.key}
                      className={cn(
                        "lisiti-itm flex items-center gap-2 rounded-lg border border-border/60 bg-muted/15 px-3 py-2.5",
                        row.isAdded && "border-dashed",
                      )}
                    >
                      <Label
                        htmlFor={`currency-balance-${row.currency_id}`}
                        className="the-code min-w-[2.75rem] shrink-0 font-semibold text-sm"
                      >
                        {row.code}
                      </Label>
                      <Input
                        id={`currency-balance-${row.currency_id}`}
                        type="text"
                        inputMode="decimal"
                        className="formatedinp h-8 flex-1 font-mono tabular-nums"
                        data-id={row.currency_id}
                        value={row.balance ?? ""}
                        readOnly={corporateView}
                        disabled={corporateView}
                        onChange={
                          corporateView
                            ? undefined
                            : (event) => {
                                const next = formatAmountInput(event.target.value);
                                setCurrencyRows((current) =>
                                  current.map((item) =>
                                    item.key === row.key ? { ...item, balance: next } : item,
                                  ),
                                );
                              }
                        }
                      />
                      {!corporateView && row.isAdded ? (
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon-sm"
                          className="remover shrink-0 text-destructive hover:bg-destructive/10 hover:text-destructive"
                          aria-label={`Remove ${row.code}`}
                          onClick={() => handleRemoveCurrency(row.currency_id, row.code)}
                        >
                          <X className="size-3.5" />
                        </Button>
                      ) : null}
                    </div>
                  ))}
                </div>

                {currencyRows.length === 0 ? (
                  <CashBalanceEmptyState
                    title="No currencies yet"
                    description={
                      corporateView
                        ? "This bank has no currency balances to display."
                        : "Use the selector below to add a currency row for this bank."
                    }
                  />
                ) : null}

                {!corporateView ? (
                  <div className="flex flex-wrap items-end gap-3 border-t border-border/50 pt-5" id="the-slector">
                    <div className="grid min-w-[10rem] gap-2">
                      <Label htmlFor="currency_id">Add currency</Label>
                      <NativeSelect
                        id="currency_id"
                        value={selectedAddCurrencyId}
                        onChange={(event) => setSelectedAddCurrencyId(event.target.value)}
                        className="w-[10rem]"
                      >
                        <NativeSelectOption value="">Please Select</NativeSelectOption>
                        {availableCurrencies.map((currency) => (
                          <NativeSelectOption key={currency.currency_id} value={String(currency.currency_id)}>
                            {currency.code}
                          </NativeSelectOption>
                        ))}
                      </NativeSelect>
                    </div>
                    <Button
                      type="button"
                      variant="secondary"
                      size="sm"
                      className="add-currency-btn gap-1.5"
                      title="Add New"
                      aria-label="Add new currency"
                      onClick={handleAddCurrency}
                    >
                      <Plus className="size-3.5" />
                      Add
                    </Button>
                  </div>
                ) : null}

                {!corporateView && showSavedMessage ? (
                  <div
                    className="the-messag flex items-center gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-emerald-700 text-sm dark:text-emerald-400"
                    role="status"
                  >
                    <CheckCircle2 className="size-4 shrink-0" />
                    <span className="font-medium">Your form has been successfully saved!</span>
                  </div>
                ) : null}
              </div>
            </div>
          ) : (
            <CashBalanceEmptyState
              title="Select a bank"
              description={
                corporateView
                  ? "Choose a bank account above to view cash balances."
                  : "Choose a bank account above to view and edit cash balances."
              }
            />
          )}
        </section>
      </div>

      {!corporateView && showFormFooter ? (
        <div className="box-footer sticky bottom-0 z-20 border-t border-border/60 bg-background/90 shadow-[0_-4px_24px_-8px_rgba(0,0,0,0.08)] backdrop-blur-md">
          <div className="flex w-full flex-wrap items-center justify-between gap-3 px-4 py-3.5 lg:px-6">
            <p className="text-muted-foreground text-xs sm:text-sm">
              Balances with empty amounts are not included when saving.
            </p>
            <div className="cash-balance-footer-actions flex flex-wrap items-center gap-2">
              <Button type="button" variant="ghost" size="sm" className="btn-cancel text-muted-foreground" onClick={handleCancel}>
                Cancel
              </Button>
              <Button
                type="button"
                id="save-record"
                size="sm"
                className="btn-save min-w-[6.5rem] px-5 shadow-sm"
                disabled={isSaving}
                onClick={() => void handleSave()}
              >
                {isSaving ? (
                  <>
                    <Loader2 className="size-3.5 animate-spin" />
                    Saving…
                  </>
                ) : (
                  "Save"
                )}
              </Button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );

}
