/**
 * Integrations Panel Component
 * Shows WhatsApp, Calendar, and CRM integration status with setup wizards
 */

"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";

interface IntegrationsPanelProps {
  lang: Lang;
  integrationStatus: any;
  onRefresh: () => void;
  onOpenIntegrationsModal?: () => void; // Opens CRMIntegrationsModal
}

export default function IntegrationsPanel({
  lang,
  integrationStatus,
  onRefresh,
  onOpenIntegrationsModal,
}: IntegrationsPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;

  const [showWhatsAppSetup, setShowWhatsAppSetup] = useState(false);

  // Setup checklist
  const setupSteps = [
    {
      id: 1,
      label: dt.setupStep1,
      completed: true,
      icon: "✅",
    },
    {
      id: 2,
      label: dt.setupStep2,
      completed: true,
      icon: "✅",
    },
    {
      id: 3,
      label: dt.setupStep3,
      completed: integrationStatus?.whatsapp?.connected || false,
      icon: integrationStatus?.whatsapp?.connected ? "✅" : "⏳",
    },
    {
      id: 4,
      label: dt.setupStep4,
      completed: false,
      icon: "⏳",
    },
    {
      id: 5,
      label: dt.setupStep5,
      completed: false,
      icon: "⏳",
    },
    {
      id: 6,
      label: dt.setupStep6,
      completed: false,
      icon: "⏳",
    },
  ];

  const completedSteps = setupSteps.filter((s) => s.completed).length;
  const setupProgress = Math.round((completedSteps / setupSteps.length) * 100);

  return (
    <div className="space-y-6">
      {/* Setup Progress */}
      <div className="rounded-xl bg-gradient-to-r from-emerald-50 to-sky-50 p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-base font-semibold text-slate-900">
              {dt.setupProgress}
            </h3>
            <p className="text-xs text-slate-600">
              {completedSteps} {isAr ? "من" : "of"} {setupSteps.length}{" "}
              {isAr ? "مكتملة" : "completed"}
            </p>
          </div>
          <div className="text-2xl font-bold text-brand-green">
            {setupProgress}%
          </div>
        </div>

        {/* Progress Bar */}
        <div className="h-3 w-full rounded-full bg-white overflow-hidden mb-4">
          <div
            className="h-full bg-gradient-to-r from-brand-green to-emerald-500 transition-all duration-500"
            style={{ width: `${setupProgress}%` }}
          ></div>
        </div>

        {/* Steps List */}
        <div className="grid gap-2 sm:grid-cols-2">
          {setupSteps.map((step) => (
            <div
              key={step.id}
              className="flex items-center gap-2 rounded-lg bg-white/80 px-3 py-2"
            >
              <span className="text-lg">{step.icon}</span>
              <span
                className={`text-xs ${step.completed ? "text-slate-700" : "text-slate-500"}`}
              >
                {step.label}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* WhatsApp Integration Card */}
      <div className="rounded-xl bg-white p-6 shadow-sm border-2 border-emerald-200">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-4">
            <div className="text-4xl">💬</div>
            <div>
              <h3 className="text-base font-semibold text-slate-900">
                {dt.whatsappIntegration}
              </h3>
              <p className="mt-1 text-xs text-slate-600">
                {dt.whatsappIntegrationDesc}
              </p>

              {/* Connection Status */}
              <div className="mt-3 flex items-center gap-2">
                <div
                  className={`h-2 w-2 rounded-full ${
                    integrationStatus?.whatsapp?.connected
                      ? "bg-emerald-500"
                      : "bg-rose-500"
                  }`}
                ></div>
                <span className="text-sm font-medium">
                  {integrationStatus?.whatsapp?.connected ? (
                    <>
                      <span className="text-emerald-700">
                        {dt.connectedStatus}
                      </span>
                      {integrationStatus.whatsapp.phoneNumber && (
                        <span className="ml-2 text-slate-600">
                          ({integrationStatus.whatsapp.phoneNumber})
                        </span>
                      )}
                    </>
                  ) : (
                    <span className="text-rose-700">
                      {dt.disconnectedStatus}
                    </span>
                  )}
                </span>
              </div>

              {/* Last Synced */}
              {integrationStatus?.whatsapp?.connectedAt && (
                <p className="mt-2 text-xs text-slate-500">
                  {dt.lastSynced}:{" "}
                  {new Date(
                    integrationStatus.whatsapp.connectedAt,
                  ).toLocaleString(isAr ? "ar-SA" : "en-US")}
                </p>
              )}

              {/* n8n Workflow Link */}
              {integrationStatus?.whatsapp?.n8nWorkflowId && (
                <a
                  href={integrationStatus.whatsapp.n8nWebhookUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-2 inline-block text-xs text-brand-green hover:underline"
                >
                  {dt.viewN8nWorkflow} →
                </a>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="flex flex-col gap-2">
            {integrationStatus?.whatsapp?.connected ? (
              <>
                <button className="rounded-lg border border-emerald-600 px-4 py-2 text-xs font-medium text-emerald-700 hover:bg-emerald-50">
                  {dt.testConnection}
                </button>
                <button className="rounded-lg border border-rose-300 px-4 py-2 text-xs font-medium text-rose-700 hover:bg-rose-50">
                  {dt.disconnect}
                </button>
              </>
            ) : (
              <button
                onClick={() => setShowWhatsAppSetup(true)}
                className="rounded-lg bg-brand-green px-4 py-2 text-xs font-semibold text-white hover:bg-brand-greenHover"
              >
                {dt.connectNow}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Calendar Integration Card */}
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-4">
            <div className="text-4xl">📅</div>
            <div>
              <h3 className="text-base font-semibold text-slate-900">
                {dt.calendarIntegration}
              </h3>
              <p className="mt-1 text-xs text-slate-600">
                {dt.calendarIntegrationDesc}
              </p>
              <div className="mt-3 flex items-center gap-2">
                <div
                  className={`h-2 w-2 rounded-full ${
                    integrationStatus?.google_calendar?.connected ||
                    integrationStatus?.outlook_calendar?.connected
                      ? "bg-emerald-500"
                      : "bg-slate-300"
                  }`}
                ></div>
                <span className="text-sm font-medium">
                  {integrationStatus?.google_calendar?.connected
                    ? isAr
                      ? "متصل بـ Google Calendar"
                      : "Connected to Google Calendar"
                    : integrationStatus?.outlook_calendar?.connected
                      ? isAr
                        ? "متصل بـ Outlook"
                        : "Connected to Outlook"
                      : isAr
                        ? "غير متصل"
                        : "Not connected"}
                </span>
              </div>
            </div>
          </div>
          <button
            onClick={onOpenIntegrationsModal}
            className={`rounded-lg px-4 py-2 text-xs font-semibold text-white ${
              integrationStatus?.google_calendar?.connected ||
              integrationStatus?.outlook_calendar?.connected
                ? "bg-emerald-600 hover:bg-emerald-700"
                : "bg-slate-600 hover:bg-slate-700"
            }`}
          >
            {integrationStatus?.google_calendar?.connected ||
            integrationStatus?.outlook_calendar?.connected
              ? isAr
                ? "إدارة"
                : "Manage"
              : dt.connectNow}
          </button>
        </div>
      </div>

      {/* CRM Integration Card */}
      <div className="rounded-xl bg-white p-6 shadow-sm">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-4">
            <div className="text-4xl">🔗</div>
            <div>
              <h3 className="text-base font-semibold text-slate-900">
                {dt.crmIntegration}
              </h3>
              <p className="mt-1 text-xs text-slate-600">
                {dt.crmIntegrationDesc}
              </p>
              <div className="mt-3 flex flex-wrap gap-2">
                <span className="text-xs text-slate-600">Salesforce</span>
                <span className="text-slate-300">•</span>
                <span className="text-xs text-slate-600">HubSpot</span>
              </div>
            </div>
          </div>
          <button
            onClick={onOpenIntegrationsModal}
            className="rounded-lg bg-slate-600 px-4 py-2 text-xs font-semibold text-white hover:bg-slate-700"
          >
            {dt.connectNow}
          </button>
        </div>
      </div>

      {/* WhatsApp Setup Modal */}
      {showWhatsAppSetup && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
          onClick={() => setShowWhatsAppSetup(false)}
        >
          <div
            className="w-full max-w-2xl rounded-xl bg-white p-6 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="text-lg font-semibold text-slate-900">
              {isAr ? "ربط واتساب للأعمال" : "Connect WhatsApp Business"}
            </h3>
            <p className="mt-2 text-sm text-slate-600">
              {isAr
                ? "أدخل معلومات سير عمل n8n الخاص بك"
                : "Enter your n8n workflow information"}
            </p>

            {/* Form */}
            <div className="mt-4 space-y-4">
              <div>
                <label className="block text-xs font-medium text-slate-700 mb-1">
                  {isAr ? "رقم واتساب للأعمال" : "WhatsApp Business Number"}
                </label>
                <input
                  type="tel"
                  placeholder="+974 XXXX XXXX"
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-slate-700 mb-1">
                  {isAr ? "رابط webhook لـ n8n" : "n8n Webhook URL"}
                </label>
                <input
                  type="url"
                  placeholder="https://your-n8n-instance.com/webhook/..."
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-slate-700 mb-1">
                  {isAr ? "معرف سير العمل (اختياري)" : "Workflow ID (optional)"}
                </label>
                <input
                  type="text"
                  placeholder="workflow_123"
                  className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                />
              </div>
            </div>

            {/* Actions */}
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => setShowWhatsAppSetup(false)}
                className="rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700"
              >
                {isAr ? "إلغاء" : "Cancel"}
              </button>
              <button className="rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover">
                {dt.connectNow}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
