"use client"

import { useState } from "react"
import {
  formatAmountCents,
  getKassenbuchCsvDownloadUrl,
  useFinancialSummaryQuery,
  useLedgerQuery,
  useOutstandingMembersQuery,
  useRecordExpenseMutation,
  useRecordPaymentMutation,
} from "@/services/finance"
import { endOfMonth, format, startOfMonth } from "date-fns"
import { useTranslations } from "next-intl"
import {
  AlertTriangle,
  Banknote,
  Download,
  Plus,
  TrendingDown,
  TrendingUp,
} from "lucide-react"

import type {
  ExpenseCategory,
  PaymentMethod,
  RecordExpenseRequest,
  RecordPaymentRequest,
} from "@/services/finance"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select } from "@/components/ui/select"

export default function FinancePage() {
  const t = useTranslations("finance")
  const now = new Date()
  const monthStart = format(startOfMonth(now), "yyyy-MM-dd")
  const monthEnd = format(endOfMonth(now), "yyyy-MM-dd")

  const { data: summary } = useFinancialSummaryQuery(monthStart, monthEnd)
  const { data: outstanding } = useOutstandingMembersQuery()
  const { data: ledger } = useLedgerQuery(monthStart, monthEnd, {
    page: 0,
    size: 10,
  })

  const [showPaymentDialog, setShowPaymentDialog] = useState(false)
  const [showExpenseDialog, setShowExpenseDialog] = useState(false)

  const recordPayment = useRecordPaymentMutation()
  const recordExpense = useRecordExpenseMutation()

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">{t("title")}</h1>
          <p className="text-muted-foreground">{t("subtitle")}</p>
        </div>
        <div className="flex gap-2">
          <Dialog open={showPaymentDialog} onOpenChange={setShowPaymentDialog}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="mr-2 h-4 w-4" />
                {t("recordPayment")}
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t("recordPayment")}</DialogTitle>
              </DialogHeader>
              <PaymentForm
                onSubmit={(data) => {
                  recordPayment.mutate(data, {
                    onSuccess: () => setShowPaymentDialog(false),
                  })
                }}
                isLoading={recordPayment.isPending}
              />
            </DialogContent>
          </Dialog>

          <Dialog open={showExpenseDialog} onOpenChange={setShowExpenseDialog}>
            <DialogTrigger asChild>
              <Button variant="outline">
                <Plus className="mr-2 h-4 w-4" />
                {t("recordExpense")}
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t("recordExpense")}</DialogTitle>
              </DialogHeader>
              <ExpenseForm
                onSubmit={(data) => {
                  recordExpense.mutate(data, {
                    onSuccess: () => setShowExpenseDialog(false),
                  })
                }}
                isLoading={recordExpense.isPending}
              />
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("totalBalance")}
            </CardTitle>
            <Banknote className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {summary ? formatAmountCents(summary.netBalanceCents) : "—"}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("incomeThisMonth")}
            </CardTitle>
            <TrendingUp className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {summary ? formatAmountCents(summary.incomeThisMonthCents) : "—"}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("expensesThisMonth")}
            </CardTitle>
            <TrendingDown className="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-red-600">
              {summary
                ? formatAmountCents(summary.expensesThisMonthCents)
                : "—"}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("outstandingMembers")}
            </CardTitle>
            <AlertTriangle className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {summary ? summary.outstandingMembersCount : "—"}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Transactions & Outstanding */}
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle>{t("recentTransactions")}</CardTitle>
            <a href={getKassenbuchCsvDownloadUrl(monthStart, monthEnd)}>
              <Button variant="ghost" size="sm">
                <Download className="mr-2 h-4 w-4" />
                CSV
              </Button>
            </a>
          </CardHeader>
          <CardContent>
            {ledger?.content && ledger.content.length > 0 ? (
              <div className="space-y-2">
                {ledger.content.map((entry) => (
                  <div
                    key={entry.id}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`rounded-full p-1.5 ${
                          entry.transactionType === "INCOME"
                            ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
                            : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"
                        }`}
                      >
                        {entry.transactionType === "INCOME" ? (
                          <TrendingUp className="h-4 w-4" />
                        ) : (
                          <TrendingDown className="h-4 w-4" />
                        )}
                      </div>
                      <div>
                        <p className="text-sm font-medium">
                          {entry.description}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {entry.transactionDate}
                        </p>
                      </div>
                    </div>
                    <span
                      className={`text-sm font-medium ${
                        entry.transactionType === "INCOME"
                          ? "text-green-600"
                          : "text-red-600"
                      }`}
                    >
                      {entry.transactionType === "INCOME" ? "+" : "-"}
                      {formatAmountCents(entry.amountCents)}
                    </span>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-center text-muted-foreground">
                {t("noTransactions")}
              </p>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t("outstandingTitle")}</CardTitle>
          </CardHeader>
          <CardContent>
            {outstanding && outstanding.length > 0 ? (
              <div className="space-y-3">
                {outstanding.slice(0, 5).map((member) => (
                  <div
                    key={member.memberId}
                    className="flex items-center justify-between"
                  >
                    <div>
                      <p className="text-sm font-medium">{member.memberName}</p>
                      <p className="text-xs text-muted-foreground">
                        {member.monthsOverdue} {t("monthsOverdue")}
                      </p>
                    </div>
                    <Badge variant="destructive">
                      {formatAmountCents(member.outstandingCents)}
                    </Badge>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-center text-sm text-muted-foreground">
                {t("noOutstanding")}
              </p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

function PaymentForm({
  onSubmit,
  isLoading,
}: {
  onSubmit: (data: RecordPaymentRequest) => void
  isLoading: boolean
}) {
  const t = useTranslations("finance")
  const [memberId, setMemberId] = useState("")
  const [amount, setAmount] = useState("")
  const [method, setMethod] = useState<PaymentMethod>("BANK_TRANSFER")
  const [periodFrom, setPeriodFrom] = useState("")
  const [periodTo, setPeriodTo] = useState("")
  const [reference, setReference] = useState("")

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit({
      memberId,
      amountCents: Math.round(parseFloat(amount) * 100),
      paymentMethod: method,
      periodFrom: periodFrom || undefined,
      periodTo: periodTo || undefined,
      reference: reference || undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label>{t("member")}</Label>
        <Input
          value={memberId}
          onChange={(e) => setMemberId(e.target.value)}
          placeholder={t("memberIdPlaceholder")}
          required
        />
      </div>
      <div className="space-y-2">
        <Label>{t("amount")}</Label>
        <Input
          type="number"
          step="0.01"
          min="0.01"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          placeholder="30.00"
          required
        />
      </div>
      <div className="space-y-2">
        <Label>{t("paymentMethod")}</Label>
        <Select
          value={method}
          onChange={(e) => setMethod(e.target.value as PaymentMethod)}
        >
          <option value="BANK_TRANSFER">{t("bankTransfer")}</option>
          <option value="CASH">{t("cash")}</option>
          <option value="SEPA">{t("sepa")}</option>
          <option value="CARD">{t("card")}</option>
        </Select>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label>{t("periodFrom")}</Label>
          <Input
            type="date"
            value={periodFrom}
            onChange={(e) => setPeriodFrom(e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label>{t("periodTo")}</Label>
          <Input
            type="date"
            value={periodTo}
            onChange={(e) => setPeriodTo(e.target.value)}
          />
        </div>
      </div>
      <div className="space-y-2">
        <Label>{t("reference")}</Label>
        <Input
          value={reference}
          onChange={(e) => setReference(e.target.value)}
          placeholder={t("referencePlaceholder")}
        />
      </div>
      <Button type="submit" disabled={isLoading} className="w-full">
        {isLoading ? t("saving") : t("recordPayment")}
      </Button>
    </form>
  )
}

function ExpenseForm({
  onSubmit,
  isLoading,
}: {
  onSubmit: (data: RecordExpenseRequest) => void
  isLoading: boolean
}) {
  const t = useTranslations("finance")
  const [category, setCategory] = useState<ExpenseCategory>("OTHER")
  const [amount, setAmount] = useState("")
  const [description, setDescription] = useState("")
  const [reference, setReference] = useState("")
  const [date, setDate] = useState(format(new Date(), "yyyy-MM-dd"))

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit({
      category,
      amountCents: Math.round(parseFloat(amount) * 100),
      description,
      reference: reference || undefined,
      transactionDate: date || undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label>{t("category")}</Label>
        <Select
          value={category}
          onChange={(e) => setCategory(e.target.value as ExpenseCategory)}
        >
          <option value="RENT">{t("categories.rent")}</option>
          <option value="UTILITIES">{t("categories.utilities")}</option>
          <option value="EQUIPMENT">{t("categories.equipment")}</option>
          <option value="SEEDS">{t("categories.seeds")}</option>
          <option value="SUPPLIES">{t("categories.supplies")}</option>
          <option value="INSURANCE">{t("categories.insurance")}</option>
          <option value="LEGAL">{t("categories.legal")}</option>
          <option value="OTHER">{t("categories.other")}</option>
        </Select>
      </div>
      <div className="space-y-2">
        <Label>{t("amount")}</Label>
        <Input
          type="number"
          step="0.01"
          min="0.01"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          placeholder="85.00"
          required
        />
      </div>
      <div className="space-y-2">
        <Label>{t("description")}</Label>
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder={t("descriptionPlaceholder")}
          required
        />
      </div>
      <div className="space-y-2">
        <Label>{t("date")}</Label>
        <Input
          type="date"
          value={date}
          onChange={(e) => setDate(e.target.value)}
          required
        />
      </div>
      <div className="space-y-2">
        <Label>{t("reference")}</Label>
        <Input
          value={reference}
          onChange={(e) => setReference(e.target.value)}
          placeholder={t("expenseReferencePlaceholder")}
        />
      </div>
      <Button type="submit" disabled={isLoading} className="w-full">
        {isLoading ? t("saving") : t("recordExpense")}
      </Button>
    </form>
  )
}
