import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Card, PageHeader } from "@/components/pbps/page";
import { ActionButton, type ActionField } from "@/components/pbps/action";
import { Tbl, View } from "@/components/pbps/blocks";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { listDurations, saveDuration } from "@/api/admin";

export const Route = createFileRoute("/p/$pid/admin/durations")({ component: Page });
const FIELDS: ActionField[] = [
  { key: "months", label: "Months (1 to 36)", type: "number", required: true },
  { key: "label", label: "Name", required: true },
];
function Page() {
  const { pid } = Route.useParams();
  const q = useQuery({ queryKey: ["durations"], queryFn: listDurations });
  return (
    <>
      <PageHeader
        title="Training durations"
        description="The lengths a training can have."
        actions={
          <>
            <Button variant="outline" asChild>
              <Link to="/p/$pid/admin/master-data" params={{ pid }}>
                Master data
              </Link>
            </Button>
            <ActionButton
              size="default"
              variant="default"
              label="New duration"
              title="New duration"
              fields={FIELDS}
              run={(v) => saveDuration({ months: Number(v["months"]), label: v["label"] ?? "" })}
              success="Duration saved"
              refresh={["durations"]}
            />
          </>
        }
      />
      <View q={q}>
        {(d) => (
          <Card padded={false}>
            <Tbl head={["Name", ">Months", "Status", ""]}>
              {d.map((x) => (
                <tr key={x.id}>
                  <td className="font-medium">{x.label}</td>
                  <td className="text-right">{x.months}</td>
                  <td>
                    <StatusBadge status={x.active ? "active" : "disabled"} />
                  </td>
                  <td className="text-right">
                    <ActionButton
                      variant="ghost"
                      label="Edit"
                      title={`Edit ${x.label}`}
                      fields={[
                        ...FIELDS,
                        {
                          key: "active",
                          label: "In use",
                          type: "select",
                          required: true,
                          options: [
                            ["yes", "Yes"],
                            ["no", "No"],
                          ],
                        },
                      ]}
                      initial={{
                        months: String(x.months),
                        label: x.label,
                        active: x.active ? "yes" : "no",
                      }}
                      run={(v) =>
                        saveDuration({
                          id: x.id,
                          months: Number(v["months"]),
                          label: v["label"] ?? "",
                          active: v["active"] === "yes",
                        })
                      }
                      success="Duration saved"
                      refresh={["durations"]}
                    />
                  </td>
                </tr>
              ))}
            </Tbl>
          </Card>
        )}
      </View>
    </>
  );
}
