"use client";

import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import type { DashboardArticleItem } from "@/components/dashboard/blogs/articles-types";
import { scheduleArticle, toggleArticleStatus } from "@/lib/api/dashboard/articles-api";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "react-toastify";

export function ArticleStatusDialog({
  item,
  open,
  onOpenChange,
}: {
  item: DashboardArticleItem | null;
  open: boolean;
  onOpenChange: (v: boolean) => void;
}) {
  const t = useTranslations("dashboard.blogs.statusDialog");
  const tc = useTranslations("dashboard.blogs.common");
  const [scheduled, setScheduled] = useState(false);
  const [date, setDate] = useState("");
  const [pending, setPending] = useState(false);

  if (!item) return null;

  const submit = async () => {
    setPending(true);
    try {
      if (scheduled) await scheduleArticle(item.id, date);
      else await toggleArticleStatus(item.id);
      toast.success(t("title"));
      onOpenChange(false);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Error");
    } finally {
      setPending(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t("title")}</DialogTitle>
        </DialogHeader>
        <label className="flex items-center gap-2 text-sm">
          <input
            type="checkbox"
            checked={scheduled}
            onChange={(e) => setScheduled(e.target.checked)}
          />
          {t("scheduleAt")}
        </label>
        {scheduled ? (
          <Input
            type="datetime-local"
            value={date}
            onChange={(e) => setDate(e.target.value)}
          />
        ) : null}
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>
            {tc("cancel")}
          </Button>
          <Button onClick={submit} disabled={pending || (scheduled && !date)}>
            {t("confirm")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
