'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import type { ScheduleJobStatus } from '@/lib/types';

type Props = {
  jobId: string;
  status: ScheduleJobStatus;
};

export function ExpenseSchedulerJobActions({ jobId, status }: Props) {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();
  const router = useRouter();

  const runAction = async (action: 'pause' | 'resume' | 'retry' | 'cancel') => {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/expense-recurring/scheduler/jobs/${jobId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action }),
      });

      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload?.error || 'تعذر تنفيذ الإجراء');
      }

      toast({
        title: 'نجاح',
        description: 'تم تنفيذ الإجراء بنجاح',
      });
      router.refresh();
    } catch (error) {
      toast({
        title: 'خطأ',
        description: error instanceof Error ? error.message : 'فشل تنفيذ الإجراء',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-wrap items-center gap-2">
      {status === 'active' ? (
        <Button size="sm" variant="outline" onClick={() => runAction('pause')} disabled={loading}>
          Pause
        </Button>
      ) : (
        <Button size="sm" variant="outline" onClick={() => runAction('resume')} disabled={loading}>
          Resume
        </Button>
      )}
      <Button size="sm" variant="secondary" onClick={() => runAction('retry')} disabled={loading}>
        Retry
      </Button>
      {status !== 'cancelled' ? (
        <Button size="sm" variant="destructive" onClick={() => runAction('cancel')} disabled={loading}>
          Cancel
        </Button>
      ) : null}
    </div>
  );
}
