"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Pencil, Plus } from "lucide-react";
import { createCurrency, updateCurrency, toggleCurrencyActive } from "./actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import type { CurrencyRate } from "@/lib/types";

export function CurrencyRowToggle({ id, isActive }: { id: string; isActive: boolean }) {
  const [pending, start] = useTransition();
  return (
    <Switch
      checked={isActive}
      disabled={pending}
      onCheckedChange={(next) =>
        start(async () => {
          await toggleCurrencyActive(id, next);
          toast.success(next ? "Activated" : "Deactivated");
        })
      }
    />
  );
}

export function CurrencyDialog({ rate }: { rate?: CurrencyRate }) {
  const editing = !!rate;
  const [open, setOpen] = useState(false);
  const [pending, startTransition] = useTransition();

  const action = editing ? updateCurrency : createCurrency;

  function onSubmit(formData: FormData) {
    startTransition(async () => {
      const res = await action(undefined, formData);
      if (res?.ok) {
        toast.success(editing ? "Rate updated" : "Rate created");
        setOpen(false);
      } else if (res?.error) {
        toast.error(res.error);
      }
    });
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {editing ? (
          <Button size="icon" variant="ghost">
            <Pencil className="size-4" />
          </Button>
        ) : (
          <Button>
            <Plus className="size-4" /> Add Rate
          </Button>
        )}
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editing ? "Edit Currency Rate" : "Add Currency Rate"}</DialogTitle>
        </DialogHeader>
        <form action={onSubmit} className="grid grid-cols-2 gap-4">
          {editing && <input type="hidden" name="id" value={rate.id} />}

          <div className="space-y-2">
            <Label htmlFor="from_currency">From currency *</Label>
            <Input
              id="from_currency"
              name="from_currency"
              defaultValue={rate?.from_currency}
              placeholder="USD"
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="to_currency">To currency *</Label>
            <Input
              id="to_currency"
              name="to_currency"
              defaultValue={rate?.to_currency}
              placeholder="INR"
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="rate">Rate *</Label>
            <Input
              id="rate"
              name="rate"
              type="number"
              step="any"
              min="0"
              defaultValue={rate?.rate ?? ""}
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="effective_date">Effective date</Label>
            <Input
              id="effective_date"
              name="effective_date"
              type="date"
              defaultValue={rate?.effective_date ?? ""}
            />
          </div>

          <div className="col-span-2 flex justify-end">
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : editing ? "Save changes" : "Save rate"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
