"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { CalendarCheckIcon, AlertCircleIcon, Loader2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { createReminderAction } from "@/actions/reminders";
import { cn } from "@/lib/utils";

interface ReviewSubmitClientProps {
  accountId: string;
  groupIds: string;
  text?: string;
  mediaId?: string;
  caption?: string;
  scheduledAt: string;
  timezone: string;
}

export function ReviewSubmitClient({
  accountId,
  groupIds,
  text,
  mediaId,
  caption,
  scheduledAt,
  timezone,
}: ReviewSubmitClientProps) {
  const router = useRouter();
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSchedule() {
    setSubmitting(true);
    setError(null);

    try {
      const result = await createReminderAction({
        accountId,
        groupIds: groupIds.split(",").filter(Boolean),
        text: text ?? null,
        mediaId: mediaId ?? null,
        caption: caption ?? null,
        scheduledAtIso: scheduledAt,
        timezone,
      });

      if (result.ok) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        router.push(`/reminders/${result.reminderId}` as any);
      } else {
        setError(result.error);
        setSubmitting(false);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An unexpected error occurred.");
      setSubmitting(false);
    }
  }

  return (
    <div className="space-y-3 pt-2">
      {error && (
        <div className="flex items-start gap-2 rounded-lg bg-destructive/10 px-3 py-2.5 text-sm text-destructive">
          <AlertCircleIcon className="size-4 shrink-0 mt-0.5" />
          <span>{error}</span>
        </div>
      )}

      <div className="flex justify-end">
        <Button
          type="button"
          size="lg"
          onClick={handleSchedule}
          disabled={submitting}
          className={cn("gap-2", submitting && "cursor-wait")}
        >
          {submitting ? (
            <>
              <Loader2Icon className="size-4 animate-spin" />
              Scheduling…
            </>
          ) : (
            <>
              <CalendarCheckIcon className="size-4" />
              Schedule Reminder
            </>
          )}
        </Button>
      </div>
    </div>
  );
}
