"use client";

import { useState, useEffect, useCallback } from "react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Recurring Quotations",
    loading: "Loading...",
    noRecurring: "No recurring quotation templates",
    noRecurringDesc: "Recurring quotations will appear here when created.",
    templateTitle: "Title",
    customer: "Customer",
    frequency: "Frequency",
    nextRun: "Next Run",
    occurrences: "Runs",
    status: "Status",
    actions: "Actions",
    pause: "Pause",
    resume: "Resume",
    cancel: "Cancel",
    ACTIVE: "Active",
    PAUSED: "Paused",
    CANCELLED: "Cancelled",
    COMPLETED: "Completed",
    MONTHLY: "Monthly",
    QUARTERLY: "Quarterly",
    SEMI_ANNUAL: "Semi-Annual",
    ANNUAL: "Annual",
    CUSTOM: "Custom",
    confirmCancel: "Are you sure you want to cancel this recurring template?",
  },
  ar: {
    title: "عروض الأسعار المتكررة",
    loading: "جاري التحميل...",
    noRecurring: "لا توجد قوالب متكررة",
    noRecurringDesc: "ستظهر عروض الأسعار المتكررة هنا عند إنشائها.",
    templateTitle: "العنوان",
    customer: "العميل",
    frequency: "التكرار",
    nextRun: "التشغيل التالي",
    occurrences: "المرات",
    status: "الحالة",
    actions: "الإجراءات",
    pause: "إيقاف مؤقت",
    resume: "استئناف",
    cancel: "إلغاء",
    ACTIVE: "نشط",
    PAUSED: "متوقف",
    CANCELLED: "ملغي",
    COMPLETED: "مكتمل",
    MONTHLY: "شهري",
    QUARTERLY: "ربع سنوي",
    SEMI_ANNUAL: "نصف سنوي",
    ANNUAL: "سنوي",
    CUSTOM: "مخصص",
    confirmCancel: "هل أنت متأكد من إلغاء هذا القالب المتكرر؟",
  },
};

const statusColors: Record<string, string> = {
  ACTIVE: "bg-green-100 text-green-700",
  PAUSED: "bg-yellow-100 text-yellow-700",
  CANCELLED: "bg-gray-100 text-gray-500",
  COMPLETED: "bg-blue-100 text-blue-700",
};

interface RecurringTemplate {
  id: string;
  title: string;
  frequency: string;
  status: string;
  nextRunDate: string;
  occurrenceCount: number;
  maxOccurrences: number | null;
  customer: { name: string } | null;
}

export function RecurringQuotationsList({ lang }: { lang: string }) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;
  const [templates, setTemplates] = useState<RecurringTemplate[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchTemplates = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/dashboard/quotations/recurring");
      const data = await res.json();
      if (data.success) {
        setTemplates(data.templates || []);
      }
    } catch (err) {
      console.error("Failed to fetch recurring templates:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  const handleAction = async (
    id: string,
    action: "pause" | "resume" | "cancel",
  ) => {
    if (action === "cancel" && !confirm(labels.confirmCancel)) {
      return;
    }

    try {
      const res = await fetchWithCSRF(
        `/api/dashboard/quotations/recurring/${id}/${action}`,
        { method: "POST" },
      );
      if (res.ok) fetchTemplates();
    } catch (err) {
      console.error(`Failed to ${action} template:`, err);
    }
  };

  if (loading) {
    return (
      <div className="py-12 text-center text-gray-500">{labels.loading}</div>
    );
  }

  if (templates.length === 0) {
    return (
      <div className="py-12 text-center">
        <p className="text-gray-900 font-medium">{labels.noRecurring}</p>
        <p className="text-gray-500 text-sm mt-1">{labels.noRecurringDesc}</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <h3 className="text-lg font-semibold text-gray-900">{labels.title}</h3>
      <div className="overflow-x-auto border border-gray-200 rounded-lg">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.templateTitle}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.customer}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.frequency}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.nextRun}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.occurrences}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.status}
              </th>
              <th className="px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-start">
                {labels.actions}
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {templates.map((tmpl) => (
              <tr key={tmpl.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 text-sm text-gray-900">
                  {tmpl.title}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {tmpl.customer?.name || "—"}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {labels[tmpl.frequency as keyof typeof labels] ||
                    tmpl.frequency}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {new Date(tmpl.nextRunDate).toLocaleDateString(
                    isAr ? "ar-QA" : "en-QA",
                  )}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {tmpl.occurrenceCount}
                  {tmpl.maxOccurrences ? `/${tmpl.maxOccurrences}` : ""}
                </td>
                <td className="px-4 py-3">
                  <span
                    className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${statusColors[tmpl.status] || ""}`}
                  >
                    {labels[tmpl.status as keyof typeof labels] || tmpl.status}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    {tmpl.status === "ACTIVE" && (
                      <button
                        onClick={() => handleAction(tmpl.id, "pause")}
                        className="text-xs text-yellow-600 hover:underline"
                      >
                        {labels.pause}
                      </button>
                    )}
                    {tmpl.status === "PAUSED" && (
                      <button
                        onClick={() => handleAction(tmpl.id, "resume")}
                        className="text-xs text-green-600 hover:underline"
                      >
                        {labels.resume}
                      </button>
                    )}
                    {(tmpl.status === "ACTIVE" || tmpl.status === "PAUSED") && (
                      <button
                        onClick={() => handleAction(tmpl.id, "cancel")}
                        className="text-xs text-red-600 hover:underline"
                      >
                        {labels.cancel}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
