"use client";



import Link from "next/link";

import { useRouter } from "next/navigation";

import { useEffect, useState } from "react";

import { Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";

import { useLocale } from "@/components/providers/locale-provider";



export interface AiClassificationView {

  intent?: string;

  sentiment?: string;

  leadTemperature?: string;

  recommendedStage?: string;

  recommendedAction?: string;

  suggestedAction?: string;

  suggestedReason?: string;

  serviceInterest?: string;

  summary?: string;

  confidence?: number;

  provider?: string;

  providerModel?: string;

}



const LABELS: Record<string, { ar: string; en: string }> = {

  intent: { ar: "النية", en: "Intent" },

  sentiment: { ar: "المشاعر", en: "Sentiment" },

  leadTemperature: { ar: "درجة الحرارة", en: "Temperature" },

  recommendedStage: { ar: "المرحلة المقترحة", en: "Suggested stage" },

  recommendedAction: { ar: "الإجراء المقترح", en: "Recommended action" },

  suggestedAction: { ar: "الإجراء المقترح", en: "Suggested action" },

  suggestedReason: { ar: "سبب الاقتراح", en: "Suggested reason" },

  serviceInterest: { ar: "اهتمام الخدمة", en: "Service interest" },

  summary: { ar: "الملخص", en: "Summary" },

  confidence: { ar: "الثقة", en: "Confidence" },

  provider: { ar: "المزود", en: "Provider" },

  providerModel: { ar: "النموذج", en: "Model" },

};



type ActionKey =

  | ""

  | "classify"

  | "lead"

  | "apply"

  | "task"

  | "stop"

  | "suppress";



export function AiClassificationPanel({

  emailReplyId,

  classification,

  threadId,

  sequenceActive,

  onRefresh,

}: {

  emailReplyId: string;

  classification?: AiClassificationView | null;

  threadId?: string;

  sequenceActive?: boolean;

  onRefresh?: () => void;

}) {

  const router = useRouter();

  const { locale } = useLocale();

  const isAr = locale === "ar";

  const [loading, setLoading] = useState<ActionKey>("");

  const [message, setMessage] = useState<string | null>(null);

  const [leadLink, setLeadLink] = useState<string | null>(null);

  const [showForce, setShowForce] = useState(false);

  const [local, setLocal] = useState(classification ?? null);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      setLocal(classification ?? null);
    }, 0);
    return () => window.clearTimeout(timeout);
  }, [classification]);

  const data = local ?? classification;

  const suggestedAction = data?.suggestedAction ?? data?.recommendedAction;



  async function convertToLead(force = false) {

    if (!emailReplyId) return;

    setLoading("lead");

    setMessage(null);

    setShowForce(false);

    const res = await fetch("/api/leads/from-email-reply", {

      method: "POST",

      headers: { "Content-Type": "application/json" },

      body: JSON.stringify({ emailReplyId, force }),

    });

    const json = await res.json();

    setLoading("");

    if (res.status === 422) {

      setMessage(json.message ?? (isAr ? "التصنيف غير مناسب لإنشاء Lead" : "Classification not suitable for lead"));

      setShowForce(true);

      return;

    }

    if (!res.ok) {

      setMessage(json.error ?? json.message ?? (isAr ? "فشل التحويل" : "Convert failed"));

      if (res.status === 409 && json.lead?._id) {

        setLeadLink(`/leads/${json.lead._id}`);

      }

      return;

    }

    const leadId = json.lead?._id;

    if (leadId) {

      setLeadLink(`/leads/${leadId}`);

      setMessage(isAr ? "تم إنشاء Lead بنجاح" : "Lead created");

      onRefresh?.();

      router.refresh();

    }

  }



  async function classifyNow() {

    if (!emailReplyId) return;

    setLoading("classify");

    setMessage(null);

    if (threadId) {

      const res = await fetch(`/api/inbox/threads/${threadId}/classify`, { method: "POST" });

      const json = await res.json();

      setLoading("");

      if (!res.ok) {

        setMessage(json.error ?? (isAr ? "فشل التصنيف" : "Classification failed"));

        return;

      }

      setLocal((json.data?.classification ?? json.classification ?? null) as AiClassificationView | null);

      setMessage(isAr ? "تم التصنيف بنجاح" : "Classified successfully");

      onRefresh?.();

      router.refresh();

      return;

    }

    const res = await fetch("/api/ai/classify-email-reply", {

      method: "POST",

      headers: { "Content-Type": "application/json" },

      body: JSON.stringify({ emailReplyId }),

    });

    const json = await res.json();

    setLoading("");

    if (!res.ok) {

      setMessage(json.error ?? (isAr ? "فشل التصنيف" : "Classification failed"));

      return;

    }

    setLocal(json.classification ?? null);

    setMessage(isAr ? "تم التصنيف بنجاح" : "Classified successfully");

    onRefresh?.();

    router.refresh();

  }



  async function createTask(title?: string) {

    if (!threadId) return;

    setLoading("task");

    setMessage(null);

    const res = await fetch(`/api/inbox/threads/${threadId}/create-task`, {

      method: "POST",

      headers: { "Content-Type": "application/json" },

      body: JSON.stringify({

        title: title ?? (isAr ? "متابعة بريد" : "Follow up email"),

      }),

    });

    const json = await res.json();

    setLoading("");

    if (!res.ok) {

      setMessage(json.error ?? (isAr ? "فشل إنشاء المهمة" : "Failed to create task"));

      return;

    }

    setMessage(isAr ? "تم إنشاء المهمة" : "Task created");

    onRefresh?.();

  }



  async function stopSequence() {

    if (!threadId) return;

    setLoading("stop");

    setMessage(null);

    const res = await fetch(`/api/inbox/threads/${threadId}/stop-sequence`, { method: "POST" });

    const json = await res.json();

    setLoading("");

    if (!res.ok) {

      setMessage(json.error ?? (isAr ? "فشل إيقاف السلسلة" : "Failed to stop sequence"));

      return;

    }

    setMessage(isAr ? "تم إيقاف السلسلة" : "Sequence stopped");

    onRefresh?.();

  }



  async function suppressSender() {

    if (!threadId) return;

    setLoading("suppress");

    setMessage(null);

    const res = await fetch(`/api/inbox/threads/${threadId}/suppress`, { method: "POST" });

    const json = await res.json();

    setLoading("");

    if (!res.ok) {

      setMessage(json.error ?? (isAr ? "فشل الاستبعاد" : "Suppress failed"));

      return;

    }

    setMessage(isAr ? "تمت إضافة المرسل إلى قائمة الاستبعاد" : "Sender suppressed");

    onRefresh?.();

  }



  async function applySuggested() {

    if (!suggestedAction) {

      setMessage(isAr ? "لا يوجد إجراء مقترح" : "No suggested action");

      return;

    }

    setLoading("apply");

    setMessage(null);

    try {

      const action = suggestedAction.toLowerCase();

      if (

        action.includes("lead") ||

        action === "send_proposal" ||

        action === "schedule_meeting" ||

        action === "send_more_info" ||

        action === "call"

      ) {

        await convertToLead(false);

        setLoading("");

        return;

      }

      if (action === "ignore" || action === "mark_unqualified") {

        if (threadId) await suppressSender();

        setLoading("");

        return;

      }

      const taskTitles: Record<string, { ar: string; en: string }> = {

        follow_up_later: { ar: "متابعة لاحقة", en: "Follow up later" },

        send_proposal: { ar: "إرسال عرض", en: "Send proposal" },

        schedule_meeting: { ar: "جدولة اجتماع", en: "Schedule meeting" },

        send_more_info: { ar: "إرسال مزيد من المعلومات", en: "Send more info" },

        call: { ar: "اتصال", en: "Call" },

      };

      const taskTitle = taskTitles[action]?.[isAr ? "ar" : "en"] ?? suggestedAction;

      if (threadId) await createTask(taskTitle);

    } finally {

      setLoading("");

    }

  }



  const busy = loading !== "";

  const label = (key: keyof typeof LABELS) =>

    LABELS[key]?.[isAr ? "ar" : "en"] ?? key;



  return (

    <section className="rounded-lg border border-border bg-card p-4">

      <h2 className="mb-3 text-sm font-semibold">

        {isAr ? "تصنيف الذكاء الاصطناعي" : "AI classification"}

      </h2>



      <div className="mb-3 flex flex-wrap gap-2">

        <Button type="button" size="sm" disabled={busy || !emailReplyId} onClick={() => void classifyNow()}>

          {loading === "classify" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}

          {isAr ? "تصنيف بالذكاء" : "AI classify"}

        </Button>

        <Button

          type="button"

          size="sm"

          variant="outline"

          disabled={busy || !suggestedAction}

          onClick={() => void applySuggested()}

        >

          {loading === "apply" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}

          {isAr ? "تطبيق الإجراء المقترح" : "Apply suggested action"}

        </Button>

        <Button

          type="button"

          size="sm"

          variant="outline"

          disabled={busy || !emailReplyId}

          onClick={() => void convertToLead(false)}

        >

          {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 || !threadId}

          onClick={() => void createTask()}

        >

          {loading === "task" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}

          {isAr ? "إنشاء مهمة" : "Create task"}

        </Button>

        {sequenceActive ? (

          <Button

            type="button"

            size="sm"

            variant="outline"

            disabled={busy || !threadId}

            onClick={() => void stopSequence()}

          >

            {loading === "stop" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}

            {isAr ? "إيقاف السلسلة" : "Stop sequence"}

          </Button>

        ) : null}

        <Button

          type="button"

          size="sm"

          variant="outline"

          disabled={busy || !threadId}

          onClick={() => void suppressSender()}

        >

          {loading === "suppress" ? <Loader2 className="h-4 w-4 animate-spin" /> : null}

          {isAr ? "إضافة إلى قائمة الاستبعاد" : "Add to suppression"}

        </Button>

      </div>



      {message ? <p className="mb-3 text-sm text-muted-foreground">{message}</p> : null}

      {showForce ? (

        <Button

          type="button"

          size="sm"

          variant="outline"

          className="mb-3"

          disabled={busy}

          onClick={() => void convertToLead(true)}

        >

          {isAr ? "إنشاء Lead بالقوة" : "Force create lead"}

        </Button>

      ) : null}

      {leadLink ? (

        <p className="mb-3 text-sm">

          <Link href={leadLink} className="text-primary hover:underline">

            {isAr ? "عرض Lead" : "View lead"}

          </Link>

        </p>

      ) : null}



      {!data ? (

        <p className="text-sm text-muted-foreground">

          {isAr ? "لم يُصنَّف هذا الرد بعد." : "This reply has not been classified yet."}

        </p>

      ) : (

        <dl className="grid gap-3 text-sm md:grid-cols-2">

          {(

            [

              "intent",

              "sentiment",

              "suggestedAction",

              "recommendedAction",

              "suggestedReason",

              "leadTemperature",

              "recommendedStage",

              "serviceInterest",

            ] as const

          ).map((key) => (

            <div key={key}>

              <dt className="text-muted-foreground">{label(key)}</dt>

              <dd className="font-medium">{String(data[key] ?? "—")}</dd>

            </div>

          ))}

          <div className="md:col-span-2">

            <dt className="text-muted-foreground">{label("summary")}</dt>

            <dd className="mt-1 whitespace-pre-wrap rounded bg-muted/40 p-2">

              {data.summary ?? "—"}

            </dd>

          </div>

          <div>

            <dt className="text-muted-foreground">{label("confidence")}</dt>

            <dd className="font-medium">

              {typeof data.confidence === "number"

                ? `${Math.round(data.confidence * 100)}%`

                : "—"}

            </dd>

          </div>

        </dl>

      )}

    </section>

  );

}

