"use client";

import { useState, useTransition } from "react";
import { toast } from "sonner";
import { Pencil, Check, X } from "lucide-react";
import {
  createMaster,
  updateMaster,
  toggleMasterActive,
} from "@/lib/master/factory";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";

export function AddMasterForm({
  table,
  revalidate,
  label,
}: {
  table: string;
  revalidate: string;
  label: string;
}) {
  const [name, setName] = useState("");
  const [pending, start] = useTransition();

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!name.trim()) return;
    start(async () => {
      const res = await createMaster(table, revalidate, name);
      if (res.ok) {
        toast.success(`${label} added`);
        setName("");
      } else {
        toast.error(res.error ?? "Failed");
      }
    });
  }

  return (
    <form onSubmit={submit} className="flex max-w-md items-end gap-2">
      <Input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder={`Enter ${label.toLowerCase()}…`}
      />
      <Button type="submit" disabled={pending}>
        {pending ? "Adding…" : "Add"}
      </Button>
    </form>
  );
}

export function MasterRowActions({
  table,
  revalidate,
  id,
  name,
  isActive,
}: {
  table: string;
  revalidate: string;
  id: string;
  name: string;
  isActive: boolean;
}) {
  const [editing, setEditing] = useState(false);
  const [value, setValue] = useState(name);
  const [pending, start] = useTransition();

  function save() {
    start(async () => {
      const res = await updateMaster(table, revalidate, id, value);
      if (res.ok) {
        toast.success("Updated");
        setEditing(false);
      } else {
        toast.error(res.error ?? "Failed");
      }
    });
  }

  function toggle(next: boolean) {
    start(async () => {
      await toggleMasterActive(table, revalidate, id, next);
      toast.success(next ? "Activated" : "Deactivated");
    });
  }

  if (editing) {
    return (
      <div className="flex items-center justify-end gap-1">
        <Input
          value={value}
          onChange={(e) => setValue(e.target.value)}
          className="h-8 w-40"
        />
        <Button size="icon" variant="ghost" onClick={save} disabled={pending}>
          <Check className="size-4" />
        </Button>
        <Button
          size="icon"
          variant="ghost"
          onClick={() => {
            setValue(name);
            setEditing(false);
          }}
        >
          <X className="size-4" />
        </Button>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-end gap-2">
      <Switch checked={isActive} onCheckedChange={toggle} disabled={pending} />
      <Button size="icon" variant="ghost" onClick={() => setEditing(true)}>
        <Pencil className="size-4" />
      </Button>
    </div>
  );
}
