"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

interface PostizPushModalProps {
  assetIds: string[];
  onClose: () => void;
}

export function PostizPushModal({ assetIds, onClose }: PostizPushModalProps) {
  const [scheduledAt, setScheduledAt] = useState(() => {
    const d = new Date();
    d.setHours(d.getHours() + 1);
    return d.toISOString().slice(0, 16);
  });
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<string | null>(null);

  async function handlePush() {
    setLoading(true);

    const res = await fetch("/api/postiz", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        assetIds,
        scheduledAt: new Date(scheduledAt).toISOString(),
      }),
    });

    const data = await res.json();

    if (res.ok) {
      const scheduled = data.results?.filter(
        (r: { status: string }) => r.status === "scheduled"
      ).length;
      setResult(`${scheduled} asset(s) scheduled successfully.`);
      setTimeout(onClose, 2000);
    } else {
      setResult(`Error: ${data.error || "Failed to push"}`);
    }

    setLoading(false);
  }

  return (
    <Dialog open onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Push to Postiz</DialogTitle>
          <DialogDescription>
            Schedule {assetIds.length} asset(s) for publishing via Postiz.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="schedule">Schedule Date & Time</Label>
            <Input
              id="schedule"
              type="datetime-local"
              value={scheduledAt}
              onChange={(e) => setScheduledAt(e.target.value)}
            />
          </div>

          {result && (
            <p
              className={`text-sm ${
                result.startsWith("Error") ? "text-red-500" : "text-green-600"
              }`}
            >
              {result}
            </p>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handlePush} disabled={loading}>
            {loading ? "Scheduling..." : "Schedule"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
