"use client"

import { useEffect, useMemo, useState, type FormEvent } from "react"
import { useTranslation } from "react-i18next"

import { DocumentNumberField } from "@/components/document-number-field"
import { InfiniteScrollSelect } from "@/components/ui/infinite-scroll-select"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useExpenseTypes } from "@/context/expense-types-context"
import { useDocumentNumberSettings } from "@/hooks/use-document-number-settings"
import {
  expenseTypeSelectValue,
  findExpenseTypeBySelectValue,
} from "@/lib/expense-types"
import { EXPENSE_METHODS, type ExpenseRow } from "@/lib/expenses"

type ExpenseFormProps = {
  formId: string
  expense: ExpenseRow
  isNew?: boolean
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
}

export function ExpenseForm({
  formId,
  expense,
  isNew = false,
  onSubmit,
}: ExpenseFormProps) {
  const { t } = useTranslation("expenses")
  const { settings: numberSettings } = useDocumentNumberSettings()
  const { expenseTypes } = useExpenseTypes()
  const activeTypes = useMemo(
    () =>
      expenseTypes.filter(
        (type) => type.status === "active" || type.apiId === expense.typeId
      ),
    [expenseTypes, expense.typeId]
  )
  const [typeId, setTypeId] = useState(() =>
    expense.typeId
      ? expenseTypeSelectValue(
          findExpenseTypeBySelectValue(activeTypes, expense.typeId) ?? {
            id: 0,
            apiId: expense.typeId,
          }
        )
      : ""
  )

  useEffect(() => {
    if (!expense.typeId) {
      setTypeId("")
      return
    }
    const match = findExpenseTypeBySelectValue(activeTypes, expense.typeId)
    setTypeId(match ? expenseTypeSelectValue(match) : expense.typeId)
  }, [expense.typeId, expense.id, activeTypes])

  const typeOptions = useMemo(
    () =>
      activeTypes.map((type) => ({
        value: expenseTypeSelectValue(type),
        label: type.name,
        description: type.description || undefined,
      })),
    [activeTypes]
  )

  const selectedType = findExpenseTypeBySelectValue(activeTypes, typeId)
  const resolvedTypeId = selectedType?.apiId?.trim() || expense.typeId || ""
  const typeName = selectedType?.name ?? expense.typeName

  return (
    <form id={formId} className="flex flex-col gap-4 text-sm" onSubmit={onSubmit}>
      <input type="hidden" name="typeId" value={resolvedTypeId} />
      <input type="hidden" name="typeName" value={typeName} />

      <div className="flex flex-col gap-2">
        <Label>{t("columns.type")}</Label>
        <InfiniteScrollSelect
          id={`${formId}-type`}
          value={typeId}
          onValueChange={setTypeId}
          options={typeOptions}
          placeholder={t("form.selectType")}
          searchPlaceholder={t("form.search")}
          emptyMessage={t("form.noTypes")}
          pageSize={10}
        />
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <DocumentNumberField
          id={`${formId}-expenseNumber`}
          name="expenseNumber"
          label={t("form.expenseNumber")}
          value={expense.expenseNumber}
          settings={numberSettings.expenses}
          isNew={isNew}
          placeholder={t("form.autoGenerated")}
          autoHint={t("form.autoGenerated")}
        />
        <div className="flex flex-col gap-2">
          <Label htmlFor={`${formId}-expenseDate`}>{t("form.expenseDate")}</Label>
          <Input
            id={`${formId}-expenseDate`}
            name="expenseDate"
            type="date"
            required
            defaultValue={expense.expenseDate}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div className="flex flex-col gap-2">
          <Label htmlFor={`${formId}-amount`}>{t("form.amount")}</Label>
          <Input
            id={`${formId}-amount`}
            name="amount"
            required
            defaultValue={expense.amount}
            placeholder="0.00"
          />
        </div>
        <div className="flex flex-col gap-2">
          <Label htmlFor={`${formId}-paymentMethod`}>{t("form.paymentMethod")}</Label>
          <select
            id={`${formId}-paymentMethod`}
            name="paymentMethod"
            defaultValue={expense.paymentMethod}
            className="border-input bg-background h-9 w-full rounded-md border px-3 text-sm shadow-xs"
          >
            {EXPENSE_METHODS.map((method) => (
              <option key={method} value={method}>
                {method}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="flex flex-col gap-2">
        <Label htmlFor={`${formId}-status`}>{t("form.status")}</Label>
        <select
          id={`${formId}-status`}
          name="status"
          defaultValue={expense.status}
          className="border-input bg-background h-9 w-full rounded-md border px-3 text-sm shadow-xs"
        >
          <option value="pending">{t("tabs.pending")}</option>
          <option value="paid">{t("tabs.paid")}</option>
          <option value="voided">{t("tabs.voided")}</option>
        </select>
      </div>

      <div className="flex flex-col gap-2">
        <Label htmlFor={`${formId}-notes`}>{t("form.notes")}</Label>
        <Input
          id={`${formId}-notes`}
          name="notes"
          defaultValue={expense.notes === "—" ? "" : expense.notes}
          placeholder={t("form.optionalNotes")}
        />
      </div>
    </form>
  )
}
