/**
 * Workflow Management Client Component
 *
 * Main dashboard for managing workflow integrations and features.
 * Displays feature cards with tier-based access control, analytics,
 * and conversation history.
 */

"use client";

import { useState, useEffect } from "react";
import {
  Zap,
  MessageSquare,
  Calendar,
  DollarSign,
  Phone,
  Users,
  Megaphone,
  TrendingUp,
  ChevronRight,
} from "lucide-react";
import WorkflowCard from "@/components/dashboard/workflow/WorkflowCard";
import AnalyticsDashboard from "@/components/dashboard/workflow/AnalyticsDashboard";
import ConversationViewer from "@/components/dashboard/workflow/ConversationViewer";
import {
  useFeatureAccess,
  getTierDisplayName,
} from "@/components/dashboard/hooks/useFeatureAccess";
import type { Lang } from "@/lib/config";

interface WorkflowManagementClientProps {
  lang: Lang;
  packageTier: string;
  userId: string;
  userEmail: string;
}

interface WorkflowData {
  id: string;
  featureType: string;
  status: "active" | "inactive" | "error";
  lastRun?: Date;
  lastRunStatus?: string;
  metrics?: {
    label: string;
    value: string | number;
    icon?: React.ReactNode;
  }[];
}

// Toast helper function
function showToast(
  type: "success" | "error" | "info" | "warning",
  title: string,
  message: string,
) {
  const event = new CustomEvent("showToast", {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}

export function WorkflowManagementClient({
  lang,
  packageTier,
  userId,
  userEmail,
}: WorkflowManagementClientProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";

  // Feature access control
  const { hasFeature, getRequiredTier, currentTier } =
    useFeatureAccess(packageTier);

  // State
  const [workflows, setWorkflows] = useState<WorkflowData[]>([]);
  const [loading, setLoading] = useState(true);
  const [activatingId, setActivatingId] = useState<string | null>(null);

  // Translations
  const t = {
    pageTitle: isAr ? "إدارة سير العمل" : "Workflow Management",
    pageSubtitle: isAr
      ? "قم بإدارة وكلائك الذكيين والتكاملات والأتمتة"
      : "Manage your AI agents, integrations, and automation",
    currentPlan: isAr ? "الخطة الحالية" : "Current Plan",
    analytics: isAr ? "التحليلات" : "Analytics",
    featuresIntegrations: isAr
      ? "الميزات والتكاملات"
      : "Features & Integrations",
    recentConversations: isAr ? "المحادثات الأخيرة" : "Recent Conversations",
    viewAll: isAr ? "عرض الكل" : "View All",
    activated: isAr ? "تم التفعيل بنجاح" : "Activated Successfully",
    deactivated: isAr ? "تم إلغاء التفعيل بنجاح" : "Deactivated Successfully",
    activationFailed: isAr ? "فشل التفعيل" : "Activation Failed",
    deactivationFailed: isAr ? "فشل إلغاء التفعيل" : "Deactivation Failed",
    pleaseWait: isAr ? "يرجى الانتظار..." : "Please wait...",
  };

  // Feature definitions with tier requirements
  const featureDefinitions = [
    // Tier 1 - Available to all
    {
      id: "ai-agent",
      featureKey: "aiAgent" as const,
      title: isAr ? "وكيل الذكاء الاصطناعي" : "AI Agent",
      description: isAr
        ? "أتمتة الردود على استفسارات العملاء بالذكاء الاصطناعي"
        : "Automate customer inquiry responses with AI",
      icon: <Zap className="h-6 w-6" />,
      color: "blue",
    },
    {
      id: "whatsapp",
      featureKey: "whatsapp" as const,
      title: isAr ? "تكامل واتساب" : "WhatsApp Integration",
      description: isAr
        ? "اربط حساب واتساب بيزنس الخاص بك"
        : "Connect your WhatsApp Business account",
      icon: <MessageSquare className="h-6 w-6" />,
      color: "green",
    },
    {
      id: "appointments",
      featureKey: "appointments" as const,
      title: isAr ? "حجز المواعيد" : "Appointment Booking",
      description: isAr
        ? "السماح للعملاء بحجز المواعيد تلقائياً"
        : "Let customers book appointments automatically",
      icon: <Calendar className="h-6 w-6" />,
      color: "purple",
    },
    // Tier 2 - Professional
    {
      id: "quotations",
      featureKey: "quotations" as const,
      title: isAr ? "عروض الأسعار" : "Quotations",
      description: isAr
        ? "توليد وإرسال عروض الأسعار تلقائياً"
        : "Generate and send price quotes automatically",
      icon: <DollarSign className="h-6 w-6" />,
      color: "yellow",
    },
    // Tier 3 - Business
    {
      id: "voice-receptionist",
      featureKey: "voiceReceptionist" as const,
      title: isAr
        ? "موظف استقبال صوتي بالذكاء الاصطناعي"
        : "AI Voice Receptionist",
      description: isAr
        ? "التعامل مع المكالمات الهاتفية بالذكاء الاصطناعي"
        : "Handle phone calls with AI voice agent",
      icon: <Phone className="h-6 w-6" />,
      color: "blue",
    },
    {
      id: "multi-staff",
      featureKey: "multiStaffLogin" as const,
      title: isAr ? "إدارة الموظفين المتعددين" : "Multi-Staff Management",
      description: isAr
        ? "إدارة فريق من موظفي الدعم"
        : "Manage team of support staff members",
      icon: <Users className="h-6 w-6" />,
      color: "indigo",
    },
    // Tier 4 - Enterprise
    {
      id: "social-management",
      featureKey: "socialManagement" as const,
      title: isAr ? "إدارة وسائل التواصل الاجتماعي" : "Social Media Management",
      description: isAr
        ? "إدارة منصات التواصل الاجتماعي المتعددة"
        : "Manage multiple social media platforms",
      icon: <Megaphone className="h-6 w-6" />,
      color: "pink",
    },
    // Tier 5 - Ultimate
    {
      id: "lead-generation",
      featureKey: "leadGeneration" as const,
      title: isAr
        ? "توليد العملاء المحتملين بالذكاء الاصطناعي"
        : "AI Lead Generation",
      description: isAr
        ? "توليد وتأهيل العملاء المحتملين تلقائياً"
        : "Automatically generate and qualify leads",
      icon: <TrendingUp className="h-6 w-6" />,
      color: "red",
    },
  ];

  // Fetch workflows from API
  useEffect(() => {
    async function fetchWorkflows() {
      try {
        setLoading(true);
        const response = await fetch("/api/dashboard/workflows");

        if (response.ok) {
          const data = await response.json();
          setWorkflows(data.workflows || []);
        } else {
          console.warn("Failed to fetch workflows, using empty state");
          setWorkflows([]);
        }
      } catch (error) {
        console.error("Error fetching workflows:", error);
        setWorkflows([]);
      } finally {
        setLoading(false);
      }
    }

    fetchWorkflows();
  }, []);

  // Get workflow data by feature ID
  const getWorkflowData = (featureId: string): WorkflowData | undefined => {
    return workflows.find((w) => w.featureType === featureId);
  };

  // Handle activate workflow
  const handleActivate = async (workflowId: string, featureId: string) => {
    setActivatingId(workflowId);

    try {
      const response = await fetch(
        `/api/dashboard/workflows/${workflowId}/activate`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        },
      );

      if (response.ok) {
        // Update local state
        setWorkflows((prev) =>
          prev.map((w) =>
            w.id === workflowId ? { ...w, status: "active" as const } : w,
          ),
        );
        showToast(
          "success",
          t.activated,
          `${featureId} ${isAr ? "تم تفعيلها" : "has been activated"}`,
        );
      } else {
        const data = await response.json();
        showToast("error", t.activationFailed, data.error || "Unknown error");
      }
    } catch (error) {
      console.error("Activation error:", error);
      showToast("error", t.activationFailed, "Network error occurred");
    } finally {
      setActivatingId(null);
    }
  };

  // Handle deactivate workflow
  const handleDeactivate = async (workflowId: string, featureId: string) => {
    setActivatingId(workflowId);

    try {
      const response = await fetch(
        `/api/dashboard/workflows/${workflowId}/activate`,
        {
          method: "DELETE",
        },
      );

      if (response.ok) {
        // Update local state
        setWorkflows((prev) =>
          prev.map((w) =>
            w.id === workflowId ? { ...w, status: "inactive" as const } : w,
          ),
        );
        showToast(
          "success",
          t.deactivated,
          `${featureId} ${isAr ? "تم إلغاء تفعيلها" : "has been deactivated"}`,
        );
      } else {
        const data = await response.json();
        showToast("error", t.deactivationFailed, data.error || "Unknown error");
      }
    } catch (error) {
      console.error("Deactivation error:", error);
      showToast("error", t.deactivationFailed, "Network error occurred");
    } finally {
      setActivatingId(null);
    }
  };

  // Handle configure workflow
  const handleConfigure = (featureId: string) => {
    // TODO: Open configuration modal or navigate to settings
    showToast(
      "info",
      isAr ? "قريباً" : "Coming Soon",
      `${featureId} ${isAr ? "الإعدادات ستتوفر قريباً" : "configuration coming soon"}`,
    );
  };

  return (
    <div className="space-y-8" dir={dir}>
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-bold text-slate-900">{t.pageTitle}</h1>
          <p className="text-slate-600 mt-1">{t.pageSubtitle}</p>
        </div>

        {/* Current Plan Badge */}
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-brand-green/10 border-2 border-brand-green/20">
          <span className="text-sm font-medium text-slate-700">
            {t.currentPlan}:
          </span>
          <span className="text-sm font-bold text-brand-green">
            {getTierDisplayName(packageTier)}
          </span>
        </div>
      </div>

      {/* Analytics Section */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-slate-900">{t.analytics}</h2>
        </div>
        <AnalyticsDashboard
          userId={userId}
          packageTier={packageTier}
          lang={lang}
        />
      </section>

      {/* Features & Integrations Section */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-slate-900">
            {t.featuresIntegrations}
          </h2>
        </div>

        {/* Feature Cards Grid */}
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {featureDefinitions.map((feature) => {
            const hasAccess = hasFeature(feature.featureKey);
            const workflowData = getWorkflowData(feature.id);
            const isLoading = activatingId === workflowData?.id;

            return (
              <WorkflowCard
                key={feature.id}
                title={feature.title}
                description={feature.description}
                icon={feature.icon}
                status={
                  !hasAccess ? "locked" : workflowData?.status || "inactive"
                }
                metrics={workflowData?.metrics}
                lastRun={workflowData?.lastRun}
                lastRunStatus={workflowData?.lastRunStatus}
                locked={!hasAccess}
                requiresUpgrade={!hasAccess}
                upgradeTier={getRequiredTier(feature.featureKey)}
                onActivate={
                  hasAccess && workflowData
                    ? () => handleActivate(workflowData.id, feature.title)
                    : undefined
                }
                onDeactivate={
                  hasAccess && workflowData
                    ? () => handleDeactivate(workflowData.id, feature.title)
                    : undefined
                }
                onConfigure={
                  hasAccess ? () => handleConfigure(feature.title) : undefined
                }
                loading={isLoading}
              />
            );
          })}
        </div>
      </section>

      {/* Recent Conversations Section */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-slate-900">
            {t.recentConversations}
          </h2>
          <button
            className="flex items-center gap-1 text-sm font-medium text-brand-green hover:text-brand-greenHover transition-colors"
            onClick={() => {
              // TODO: Navigate to full conversations page
              showToast("info", t.viewAll, isAr ? "قريباً" : "Coming soon");
            }}
          >
            {t.viewAll}
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>
        <ConversationViewer userId={userId} lang={lang} />
      </section>
    </div>
  );
}
