"use client";

import {
  ChevronRight,
  Zap,
  MessageSquare,
  Calendar as CalendarIcon,
  DollarSign,
  Phone,
  Users,
  Megaphone,
  TrendingUp,
} from "lucide-react";
import dynamic from "next/dynamic";
import type { Session } from "next-auth";
import type { Lang } from "@/lib/config";
import type { FeatureName } from "@/components/dashboard/hooks/useFeatureAccess";
import { getTierDisplayName as getTierName } from "@/components/dashboard/hooks/useFeatureAccess";
import type {
  WorkflowData,
  FeatureDefinition,
} from "@/lib/types/dashboard.types";
const AnalyticsDashboard = dynamic(
  () => import("@/components/dashboard/workflow/AnalyticsDashboard"),
  {
    ssr: false,
  },
);

const WorkflowCard = dynamic(
  () => import("@/components/dashboard/workflow/WorkflowCard"),
  {
    ssr: false,
  },
);

const ConversationViewer = dynamic(
  () => import("@/components/dashboard/workflow/ConversationViewer"),
  {
    ssr: false,
  },
);

interface WorkflowsTabProps {
  lang: Lang;
  isAr: boolean;
  packageTier: string;
  workflows: WorkflowData[];
  activatingWorkflowId: string | null;
  hasFeature: (feature: FeatureName) => boolean;
  getRequiredTier: (feature: FeatureName) => string;
  onActivate: (workflowId: string, featureTitle: string) => Promise<void>;
  onDeactivate: (workflowId: string, featureTitle: string) => Promise<void>;
  onConfigure: (featureTitle: string) => void;
  onOpenWhatsApp: () => void;
  session: Session;
}

export function WorkflowsTab({
  lang,
  isAr,
  packageTier,
  workflows,
  activatingWorkflowId,
  hasFeature,
  getRequiredTier,
  onActivate,
  onDeactivate,
  onConfigure,
  onOpenWhatsApp,
  session,
}: WorkflowsTabProps) {
  const featureDefinitions: FeatureDefinition[] = [
    {
      id: "ai-agent",
      featureKey: "aiAgent",
      title: isAr ? "وكيل الذكاء الاصطناعي" : "AI Agent",
      description: isAr
        ? "أتمتة الردود على استفسارات العملاء"
        : "Automate customer inquiry responses",
      icon: <Zap className="h-6 w-6" />,
      color: "blue",
    },
    {
      id: "whatsapp",
      featureKey: "whatsapp",
      title: isAr ? "تكامل واتساب" : "WhatsApp Integration",
      description: isAr
        ? "اربط حساب واتساب بيزنس"
        : "Connect WhatsApp Business",
      icon: <MessageSquare className="h-6 w-6" />,
      color: "green",
    },
    {
      id: "appointments",
      featureKey: "appointments",
      title: isAr ? "حجز المواعيد" : "Appointment Booking",
      description: isAr
        ? "حجز تلقائي للمواعيد"
        : "Automatic appointment booking",
      icon: <CalendarIcon className="h-6 w-6" />,
      color: "purple",
    },
    {
      id: "quotations",
      featureKey: "quotations",
      title: isAr ? "عروض الأسعار" : "Quotations",
      description: isAr
        ? "توليد عروض أسعار تلقائية"
        : "Auto-generate price quotes",
      icon: <DollarSign className="h-6 w-6" />,
      color: "yellow",
    },
    {
      id: "voice-receptionist",
      featureKey: "voiceReceptionist",
      title: isAr ? "موظف استقبال صوتي" : "AI Voice Receptionist",
      description: isAr
        ? "التعامل مع المكالمات بالذكاء الاصطناعي"
        : "Handle calls with AI",
      icon: <Phone className="h-6 w-6" />,
      color: "blue",
    },
    {
      id: "multi-staff",
      featureKey: "multiStaffLogin",
      title: isAr ? "إدارة الموظفين" : "Multi-Staff Management",
      description: isAr ? "إدارة فريق الدعم" : "Manage support team",
      icon: <Users className="h-6 w-6" />,
      color: "indigo",
    },
    {
      id: "social-management",
      featureKey: "socialManagement",
      title: isAr ? "وسائل التواصل" : "Social Media",
      description: isAr ? "إدارة منصات متعددة" : "Manage multiple platforms",
      icon: <Megaphone className="h-6 w-6" />,
      color: "pink",
    },
    {
      id: "lead-generation",
      featureKey: "leadGeneration",
      title: isAr ? "توليد العملاء" : "AI Lead Generation",
      description: isAr ? "توليد وتأهيل العملاء" : "Generate and qualify leads",
      icon: <TrendingUp className="h-6 w-6" />,
      color: "red",
    },
  ];

  const getWorkflowData = (featureId: string): WorkflowData | undefined =>
    workflows.find((w) => w.featureType === featureId);

  return (
    <div className="space-y-8 animate-fadeIn">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">
            {isAr ? "إدارة سير العمل" : "Workflow Management"}
          </h2>
          <p className="text-slate-600 mt-1">
            {isAr
              ? "قم بإدارة وكلائك الذكيين والتكاملات"
              : "Manage your AI agents and integrations"}
          </p>
        </div>
        <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">
            {isAr ? "الخطة الحالية" : "Current Plan"}:
          </span>
          <span className="text-sm font-bold text-brand-green">
            {getTierName(packageTier)}
          </span>
        </div>
      </div>

      <section>
        <h3 className="text-xl font-bold text-slate-900 mb-4">
          {isAr ? "التحليلات" : "Analytics"}
        </h3>
        <AnalyticsDashboard
          userId={session.user?.id || ""}
          packageTier={packageTier}
          lang={lang}
        />
      </section>

      <section>
        <h3 className="text-xl font-bold text-slate-900 mb-4">
          {isAr ? "الميزات والتكاملات" : "Features & Integrations"}
        </h3>
        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {featureDefinitions.map((feature) => {
            const hasAccess = hasFeature(feature.featureKey as FeatureName);
            const workflowData = getWorkflowData(feature.id);
            const isLoading = activatingWorkflowId === 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 as FeatureName)}
                onActivate={
                  hasAccess && workflowData
                    ? () => onActivate(workflowData.id, feature.title)
                    : undefined
                }
                onDeactivate={
                  hasAccess && workflowData
                    ? () => onDeactivate(workflowData.id, feature.title)
                    : undefined
                }
                onConfigure={
                  hasAccess ? () => onConfigure(feature.title) : undefined
                }
                loading={isLoading}
              />
            );
          })}
        </div>
      </section>

      <section>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-xl font-bold text-slate-900">
            {isAr ? "المحادثات الأخيرة" : "Recent Conversations"}
          </h3>
          <button
            className="flex items-center gap-1 text-sm font-medium text-brand-green hover:text-brand-greenHover transition-colors"
            onClick={onOpenWhatsApp}
          >
            {isAr ? "عرض الكل" : "View All"}
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>
        <ConversationViewer userId={session.user?.id || ""} lang={lang} />
      </section>
    </div>
  );
}

export default WorkflowsTab;
