"use client"

import { useState } from "react"
import {
  formatAmountCents,
  useCreateFeeScheduleMutation,
  useDeactivateFeeScheduleMutation,
  useFeeSchedulesQuery,
} from "@/services/finance"
import { useTranslations } from "next-intl"
import { Plus, Power } from "lucide-react"

import type { CreateFeeScheduleRequest, FeeInterval } 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 FeeSchedulesPage() {
  const t = useTranslations("finance")
  const { data: schedules, isLoading } = useFeeSchedulesQuery()
  const createMutation = useCreateFeeScheduleMutation()
  const deactivateMutation = useDeactivateFeeScheduleMutation()
  const [showCreate, setShowCreate] = useState(false)

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{t("feeSchedules")}</h1>
        <Dialog open={showCreate} onOpenChange={setShowCreate}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              {t("createFeeSchedule")}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t("createFeeSchedule")}</DialogTitle>
            </DialogHeader>
            <FeeScheduleForm
              onSubmit={(data) => {
                createMutation.mutate(data, {
                  onSuccess: () => setShowCreate(false),
                })
              }}
              isLoading={createMutation.isPending}
            />
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {schedules?.map((schedule) => (
          <Card key={schedule.id}>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-base">{schedule.name}</CardTitle>
              {schedule.isDefault && (
                <Badge variant="secondary">{t("default")}</Badge>
              )}
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="text-2xl font-bold">
                  {formatAmountCents(schedule.amountCents)}
                </div>
                <div className="text-sm text-muted-foreground">
                  {t(`interval.${schedule.interval}`)}
                </div>
                {schedule.description && (
                  <p className="text-sm text-muted-foreground">
                    {schedule.description}
                  </p>
                )}
                <div className="flex gap-2 pt-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => deactivateMutation.mutate(schedule.id)}
                    disabled={!schedule.active}
                  >
                    <Power className="mr-1 h-3 w-3" />
                    {t("deactivate")}
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
        {!schedules?.length && !isLoading && (
          <p className="col-span-full text-center text-muted-foreground">
            {t("noFeeSchedules")}
          </p>
        )}
      </div>
    </div>
  )
}

function FeeScheduleForm({
  onSubmit,
  isLoading,
}: {
  onSubmit: (data: CreateFeeScheduleRequest) => void
  isLoading: boolean
}) {
  const t = useTranslations("finance")
  const [name, setName] = useState("")
  const [amount, setAmount] = useState("")
  const [interval, setInterval] = useState<FeeInterval>("MONTHLY")
  const [description, setDescription] = useState("")

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

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label>{t("scheduleName")}</Label>
        <Input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder={t("scheduleNamePlaceholder")}
          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("intervalLabel")}</Label>
        <Select
          value={interval}
          onChange={(e) => setInterval(e.target.value as FeeInterval)}
        >
          <option value="MONTHLY">{t("interval.MONTHLY")}</option>
          <option value="QUARTERLY">{t("interval.QUARTERLY")}</option>
          <option value="YEARLY">{t("interval.YEARLY")}</option>
          <option value="ONE_TIME">{t("interval.ONE_TIME")}</option>
        </Select>
      </div>
      <div className="space-y-2">
        <Label>{t("description")}</Label>
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder={t("scheduleDescPlaceholder")}
        />
      </div>
      <Button type="submit" disabled={isLoading} className="w-full">
        {isLoading ? t("saving") : t("createFeeSchedule")}
      </Button>
    </form>
  )
}
