/**
 * Workflow Activation Step - Enable AI workflows based on tier
 */

"use client";

import { useState, useEffect } from "react";
import {
  Workflow,
  Zap,
  MessageSquare,
  Calendar,
  DollarSign,
  Phone,
  Users,
  Lock,
  CheckCircle2,
} from "lucide-react";
import type { Lang } from "@/lib/config";

interface WorkflowActivationStepProps {
  lang: Lang;
  packageTier: string;
  onContinue: () => void;
}

export default function WorkflowActivationStep({
  lang,
  packageTier,
  onContinue,
}: WorkflowActivationStepProps) {
  const isAr = lang === "ar";
  const [workflows, setWorkflows] = useState<any[]>([]);
  const [activating, setActivating] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const t = {
    title: isAr ? "تفعيل سير العمل" : "Activate Workflows",
    subtitle: isAr
      ? "اختر الميزات التي تريد تفعيلها"
      : "Choose which features to enable",
    currentPlan: isAr ? "خطتك الحالية" : "Your Current Plan",
    active: isAr ? "نشط" : "Active",
    inactive: isAr ? "غير نشط" : "Inactive",
    locked: isAr ? "مقفل" : "Locked",
    activate: isAr ? "تفعيل" : "Activate",
    deactivate: isAr ? "إلغاء التفعيل" : "Deactivate",
    upgradeRequired: isAr ? "يتطلب ترقية" : "Upgrade Required",
    continueBtn: isAr ? "متابعة" : "Continue",
  };

  const workflowDefinitions = [
    {
      id: "ai-agent",
      icon: <Zap className="w-6 h-6" />,
      title: isAr ? "وكيل الذكاء الاصطناعي" : "AI Agent",
      description: isAr ? "ردود تلقائية ذكية" : "Smart automated responses",
      requiredTier: "tier1",
    },
    {
      id: "whatsapp",
      icon: <MessageSquare className="w-6 h-6" />,
      title: isAr ? "تكامل واتساب" : "WhatsApp Integration",
      description: isAr ? "اتصال واتساب بيزنس" : "WhatsApp Business connection",
      requiredTier: "tier1",
    },
    {
      id: "appointments",
      icon: <Calendar className="w-6 h-6" />,
      title: isAr ? "حجز المواعيد" : "Appointment Booking",
      description: isAr
        ? "حجز تلقائي للمواعيد"
        : "Automatic appointment scheduling",
      requiredTier: "tier1",
    },
    {
      id: "quotations",
      icon: <DollarSign className="w-6 h-6" />,
      title: isAr ? "عروض الأسعار" : "Quotations",
      description: isAr
        ? "توليد عروض أسعار تلقائية"
        : "Auto-generate price quotes",
      requiredTier: "tier2",
    },
    {
      id: "voice-receptionist",
      icon: <Phone className="w-6 h-6" />,
      title: isAr ? "موظف استقبال صوتي" : "Voice Receptionist",
      description: isAr ? "مكالمات ذكية" : "AI-powered calls",
      requiredTier: "tier2",
    },
    {
      id: "multi-staff",
      icon: <Users className="w-6 h-6" />,
      title: isAr ? "إدارة الموظفين" : "Multi-Staff",
      description: isAr ? "إدارة فريق الدعم" : "Team management",
      requiredTier: "tier3",
    },
  ];

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

  const loadWorkflows = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/dashboard/workflows");
      if (response.ok) {
        const data = await response.json();
        setWorkflows(data.workflows || []);
      }
    } catch (error) {
      console.error("Error loading workflows:", error);
    } finally {
      setLoading(false);
    }
  };

  const isWorkflowActive = (workflowId: string) => {
    return workflows.some(
      (w) => w.featureType === workflowId && w.status === "active",
    );
  };

  const isWorkflowLocked = (requiredTier: string) => {
    const tierLevels: Record<string, number> = { tier1: 1, tier2: 2, tier3: 3 };
    return tierLevels[requiredTier] > (tierLevels[packageTier] || 1);
  };

  const handleToggleWorkflow = async (
    workflowId: string,
    currentlyActive: boolean,
  ) => {
    setActivating(workflowId);
    try {
      const workflow = workflows.find((w) => w.featureType === workflowId);
      if (!workflow) return;

      const endpoint = currentlyActive
        ? `/api/dashboard/workflows/${workflow.id}/activate`
        : `/api/dashboard/workflows/${workflow.id}/activate`;

      const response = await fetch(endpoint, {
        method: currentlyActive ? "DELETE" : "POST",
      });

      if (response.ok) {
        await loadWorkflows();
      }
    } catch (error) {
      console.error("Error toggling workflow:", error);
    } finally {
      setActivating(null);
    }
  };

  return (
    <div className="space-y-8 animate-fadeIn">
      {/* Header */}
      <div className="text-center">
        <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 shadow-lg shadow-indigo-500/25 mb-6">
          <Workflow className="w-8 h-8 text-white" />
        </div>
        <h2 className="text-3xl font-bold text-slate-900 mb-3">{t.title}</h2>
        <p className="text-lg text-slate-600 mb-4">{t.subtitle}</p>
        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-brand-green/10 border 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">
            {packageTier}
          </span>
        </div>
      </div>

      {/* Workflows Grid */}
      <div className="grid gap-4 sm:grid-cols-2">
        {workflowDefinitions.map((workflow) => {
          const isActive = isWorkflowActive(workflow.id);
          const isLocked = isWorkflowLocked(workflow.requiredTier);
          const isActivatingThis = activating === workflow.id;

          return (
            <div
              key={workflow.id}
              className={`p-6 rounded-2xl border-2 transition-all ${
                isActive
                  ? "border-brand-green bg-brand-green/5"
                  : isLocked
                    ? "border-slate-200 bg-slate-50 opacity-75"
                    : "border-slate-200 bg-white hover:border-slate-300"
              }`}
            >
              <div className="flex items-start justify-between mb-4">
                <div
                  className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                    isActive
                      ? "bg-brand-green text-white"
                      : isLocked
                        ? "bg-slate-200 text-slate-400"
                        : "bg-slate-100 text-slate-600"
                  }`}
                >
                  {isLocked ? <Lock className="w-6 h-6" /> : workflow.icon}
                </div>
                {isActive && (
                  <CheckCircle2 className="w-6 h-6 text-brand-green" />
                )}
              </div>

              <h3 className="text-lg font-bold text-slate-900 mb-2">
                {workflow.title}
              </h3>
              <p className="text-sm text-slate-600 mb-4">
                {workflow.description}
              </p>

              {isLocked ? (
                <div className="text-xs font-medium text-amber-600 bg-amber-50 px-3 py-2 rounded-lg border border-amber-200">
                  {t.upgradeRequired}
                </div>
              ) : (
                <button
                  onClick={() => handleToggleWorkflow(workflow.id, isActive)}
                  disabled={isActivatingThis}
                  className={`w-full px-4 py-2 rounded-lg font-semibold text-sm transition-all ${
                    isActive
                      ? "bg-slate-100 text-slate-700 hover:bg-slate-200"
                      : "bg-brand-green text-white hover:bg-brand-greenHover"
                  } disabled:opacity-50 disabled:cursor-not-allowed`}
                >
                  {isActivatingThis
                    ? "..."
                    : isActive
                      ? t.deactivate
                      : t.activate}
                </button>
              )}
            </div>
          );
        })}
      </div>

      {/* Continue Button */}
      <div className="flex justify-center pt-4">
        <button
          onClick={onContinue}
          className="inline-flex items-center gap-2 px-8 py-4 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-white font-semibold shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
        >
          {t.continueBtn}
          <span className="text-xl">{isAr ? "←" : "→"}</span>
        </button>
      </div>

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.4s ease-out forwards;
        }
      `}</style>
    </div>
  );
}
