"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLocale } from "@/components/providers/locale-provider";

type ActionKey = "" | "status" | "task" | "classify" | "lead";

export function InboxMessageActions({
  emailId,
  currentStatus,
  subject,
  onClassify,
  onConvertLead,
}: {
  emailId: string;
  currentStatus: string;
  subject?: string;
  onClassify?: () => void;
  onConvertLead?: () => void;
}) {
  const router = useRouter();
  const { locale } = useLocale();
  const isAr = locale === "ar";
  const [loading, setLoading] = useState<ActionKey>("");
  const [message, setMessage] = useState<string | null>(null);

  async function updateStatus(nextStatus: string) {
    setLoading("status");
    setMessage(null);
    const res = await fetch(`/api/inbox/${emailId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: nextStatus }),
    });
    const json = await res.json();
    setLoading("");
    if (!res.ok) {
      setMessage(json.error ?? (isAr ? "فشل تحديث الحالة" : "Status update failed"));
      return;
    }
    setMessage(isAr ? "تم تحديث الحالة" : "Status updated");
    router.refresh();
  }

  async function createFollowUpTask() {
    setLoading("task");
    setMessage(null);
    const title = isAr
      ? `رد على: ${subject?.trim() || "بريد وارد"}`
      : `Reply to: ${subject?.trim() || "inbox message"}`;
    const res = await fetch("/api/tasks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title,
        description: isAr ? "متابعة رد من صندوق الوارد" : "Follow up on inbox reply",
        relatedEntityType: "email",
        relatedEntityId: emailId,
      }),
    });
    const json = await res.json();
    setLoading("");
    if (!res.ok) {
      setMessage(json.error ?? (isAr ? "فشل إنشاء المهمة" : "Failed to create task"));
      return;
    }
    setMessage(isAr ? "تم إنشاء المهمة" : "Task created");
    router.refresh();
  }

  const busy = loading !== "";

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap gap-2">
        <Button
          type="button"
          size="sm"
          disabled={busy}
          onClick={() => {
            if (onClassify) onClassify();
            else void (async () => {
              setLoading("classify");
              const res = await fetch("/api/ai/classify-email-reply", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ emailReplyId: emailId }),
              });
              setLoading("");
              if (res.ok) router.refresh();
            })();
          }}
        >
          {loading === "classify" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          {isAr ? "تصنيف بالذكاء" : "AI classify"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => {
            if (onConvertLead) {
              onConvertLead();
              return;
            }
            void (async () => {
              setLoading("lead");
              const res = await fetch("/api/leads/from-email-reply", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ emailReplyId: emailId }),
              });
              setLoading("");
              if (res.ok) router.refresh();
              else {
                const json = await res.json();
                setMessage(json.error ?? json.message ?? (isAr ? "فشل التحويل" : "Convert failed"));
              }
            })();
          }}
        >
          {loading === "lead" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          {isAr ? "تحويل إلى Lead" : "Convert to lead"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => void createFollowUpTask()}
        >
          {loading === "task" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          {isAr ? "إنشاء مهمة" : "Create task"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => void updateStatus("ignored")}
        >
          {isAr ? "تجاهل" : "Ignore"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => void updateStatus("spam")}
        >
          {isAr ? "أرشفة" : "Archive"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="outline"
          disabled={busy}
          onClick={() => void createFollowUpTask()}
        >
          {isAr ? "رد لاحقاً" : "Reply later"}
        </Button>
      </div>
      <p className="text-xs text-muted-foreground">
        {isAr ? "الحالة:" : "Status:"} {currentStatus}
      </p>
      {message ? <p className="text-sm text-muted-foreground">{message}</p> : null}
    </div>
  );
}
