/**
 * Workflow Configuration Modal
 *
 * Modal dialog for configuring individual workflow settings.
 * Supports different configuration options based on feature type.
 */

"use client";

import { useState, useEffect, Fragment } from "react";
import { Dialog, Transition } from "@headlessui/react";
import {
  X,
  Save,
  Loader2,
  Zap,
  MessageSquare,
  Calendar,
  DollarSign,
  Phone,
  Users,
  Megaphone,
  TrendingUp,
  Settings,
  Bell,
  Clock,
  Globe,
} from "lucide-react";

interface WorkflowConfigModalProps {
  isOpen: boolean;
  onClose: () => void;
  featureId: string;
  featureTitle: string;
  lang: "ar" | "en";
  onSave: (config: Record<string, unknown>) => Promise<void>;
}

// Feature icon mapping
const FEATURE_ICONS: Record<string, React.ReactNode> = {
  "ai-agent": <Zap className="h-6 w-6" />,
  whatsapp: <MessageSquare className="h-6 w-6" />,
  appointments: <Calendar className="h-6 w-6" />,
  quotations: <DollarSign className="h-6 w-6" />,
  "voice-receptionist": <Phone className="h-6 w-6" />,
  "multi-staff": <Users className="h-6 w-6" />,
  "social-management": <Megaphone className="h-6 w-6" />,
  "lead-generation": <TrendingUp className="h-6 w-6" />,
};

export default function WorkflowConfigModal({
  isOpen,
  onClose,
  featureId,
  featureTitle,
  lang,
  onSave,
}: WorkflowConfigModalProps) {
  const isAr = lang === "ar";
  const [saving, setSaving] = useState(false);
  const [config, setConfig] = useState<Record<string, unknown>>({});
  const [loading, setLoading] = useState(true);

  // Translations
  const t = {
    configureTitle: isAr ? "إعدادات" : "Configure",
    cancel: isAr ? "إلغاء" : "Cancel",
    save: isAr ? "حفظ" : "Save",
    saving: isAr ? "جارٍ الحفظ..." : "Saving...",
    loading: isAr ? "جارٍ التحميل..." : "Loading...",
    generalSettings: isAr ? "الإعدادات العامة" : "General Settings",
    notifications: isAr ? "الإشعارات" : "Notifications",
    scheduling: isAr ? "الجدولة" : "Scheduling",
    language: isAr ? "اللغة" : "Language",
    enableNotifications: isAr ? "تفعيل الإشعارات" : "Enable Notifications",
    notificationsDesc: isAr
      ? "استلام إشعارات عند وقوع أحداث مهمة"
      : "Receive notifications when important events occur",
    autoResponse: isAr ? "الرد التلقائي" : "Auto Response",
    autoResponseDesc: isAr
      ? "الرد تلقائياً على الرسائل الواردة"
      : "Automatically respond to incoming messages",
    workingHours: isAr ? "ساعات العمل" : "Working Hours",
    workingHoursDesc: isAr ? "تحديد ساعات التشغيل" : "Define operational hours",
    responseLanguage: isAr ? "لغة الرد" : "Response Language",
    responseLanguageDesc: isAr
      ? "اختر لغة الردود الآلية"
      : "Choose the language for automated responses",
    arabic: isAr ? "العربية" : "Arabic",
    english: isAr ? "الإنجليزية" : "English",
    both: isAr ? "كلاهما" : "Both",
    from: isAr ? "من" : "From",
    to: isAr ? "إلى" : "To",
  };

  // Fetch existing configuration
  useEffect(() => {
    async function fetchConfig() {
      if (!isOpen) return;

      setLoading(true);
      try {
        const response = await fetch(
          `/api/dashboard/workflows/${featureId}/config`,
        );
        if (response.ok) {
          const data = await response.json();
          setConfig(data.config || {});
        } else {
          // Use default config
          setConfig({
            enabled: true,
            notifications: true,
            autoResponse: false,
            language: "both",
            workingHours: {
              start: "09:00",
              end: "17:00",
            },
          });
        }
      } catch (error) {
        console.error("Error fetching config:", error);
        setConfig({
          enabled: true,
          notifications: true,
          autoResponse: false,
          language: "both",
          workingHours: {
            start: "09:00",
            end: "17:00",
          },
        });
      } finally {
        setLoading(false);
      }
    }

    fetchConfig();
  }, [isOpen, featureId]);

  const handleSave = async () => {
    setSaving(true);
    try {
      await onSave(config);
      onClose();
    } catch (error) {
      console.error("Error saving config:", error);
    } finally {
      setSaving(false);
    }
  };

  const updateConfig = (key: string, value: unknown) => {
    setConfig((prev) => ({ ...prev, [key]: value }));
  };

  const updateWorkingHours = (field: "start" | "end", value: string) => {
    setConfig((prev) => ({
      ...prev,
      workingHours: {
        ...((prev.workingHours as Record<string, string>) || {}),
        [field]: value,
      },
    }));
  };

  return (
    <Transition show={isOpen} as={Fragment}>
      <Dialog onClose={onClose} className="relative z-50">
        {/* Backdrop */}
        <Transition.Child
          as={Fragment}
          enter="ease-out duration-300"
          enterFrom="opacity-0"
          enterTo="opacity-100"
          leave="ease-in duration-200"
          leaveFrom="opacity-100"
          leaveTo="opacity-0"
        >
          <div className="fixed inset-0 bg-black/50" />
        </Transition.Child>

        {/* Modal */}
        <div className="fixed inset-0 flex items-center justify-center p-4">
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0 scale-95"
            enterTo="opacity-100 scale-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100 scale-100"
            leaveTo="opacity-0 scale-95"
          >
            <Dialog.Panel
              className="w-full max-w-lg bg-white rounded-2xl shadow-xl overflow-hidden"
              dir={isAr ? "rtl" : "ltr"}
            >
              {/* Header */}
              <div className="flex items-center justify-between p-6 border-b border-slate-200 bg-gradient-to-r from-brand-green/5 to-emerald-50">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-xl bg-brand-green/10 text-brand-green">
                    {FEATURE_ICONS[featureId] || (
                      <Settings className="h-6 w-6" />
                    )}
                  </div>
                  <div>
                    <Dialog.Title className="text-lg font-bold text-slate-900">
                      {t.configureTitle} {featureTitle}
                    </Dialog.Title>
                  </div>
                </div>
                <button
                  onClick={onClose}
                  className="p-2 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              {/* Content */}
              <div className="p-6 space-y-6 max-h-[60vh] overflow-y-auto">
                {loading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-8 w-8 text-brand-green animate-spin" />
                    <span className="ms-2 text-slate-600">{t.loading}</span>
                  </div>
                ) : (
                  <>
                    {/* General Settings Section */}
                    <div className="space-y-4">
                      <h3 className="flex items-center gap-2 text-sm font-semibold text-slate-700 uppercase tracking-wide">
                        <Settings className="h-4 w-4" />
                        {t.generalSettings}
                      </h3>

                      {/* Notifications Toggle */}
                      <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50 border border-slate-200">
                        <div className="flex items-center gap-3">
                          <Bell className="h-5 w-5 text-slate-500" />
                          <div>
                            <p className="font-medium text-slate-900">
                              {t.enableNotifications}
                            </p>
                            <p className="text-sm text-slate-500">
                              {t.notificationsDesc}
                            </p>
                          </div>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={config.notifications as boolean}
                            onChange={(e) =>
                              updateConfig("notifications", e.target.checked)
                            }
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-green/25 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-green" />
                        </label>
                      </div>

                      {/* Auto Response Toggle */}
                      <div className="flex items-center justify-between p-4 rounded-xl bg-slate-50 border border-slate-200">
                        <div className="flex items-center gap-3">
                          <Zap className="h-5 w-5 text-slate-500" />
                          <div>
                            <p className="font-medium text-slate-900">
                              {t.autoResponse}
                            </p>
                            <p className="text-sm text-slate-500">
                              {t.autoResponseDesc}
                            </p>
                          </div>
                        </div>
                        <label className="relative inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={config.autoResponse as boolean}
                            onChange={(e) =>
                              updateConfig("autoResponse", e.target.checked)
                            }
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-green/25 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-green" />
                        </label>
                      </div>
                    </div>

                    {/* Scheduling Section */}
                    <div className="space-y-4">
                      <h3 className="flex items-center gap-2 text-sm font-semibold text-slate-700 uppercase tracking-wide">
                        <Clock className="h-4 w-4" />
                        {t.scheduling}
                      </h3>

                      <div className="p-4 rounded-xl bg-slate-50 border border-slate-200">
                        <div className="flex items-center gap-3 mb-3">
                          <Clock className="h-5 w-5 text-slate-500" />
                          <div>
                            <p className="font-medium text-slate-900">
                              {t.workingHours}
                            </p>
                            <p className="text-sm text-slate-500">
                              {t.workingHoursDesc}
                            </p>
                          </div>
                        </div>
                        <div className="flex items-center gap-3">
                          <div className="flex-1">
                            <label className="block text-xs text-slate-500 mb-1">
                              {t.from}
                            </label>
                            <input
                              type="time"
                              value={
                                (config.workingHours as Record<string, string>)
                                  ?.start || "09:00"
                              }
                              onChange={(e) =>
                                updateWorkingHours("start", e.target.value)
                              }
                              className="w-full px-3 py-2 rounded-lg border border-slate-300 text-slate-900 focus:border-brand-green focus:ring-2 focus:ring-brand-green/25 focus:outline-none"
                            />
                          </div>
                          <div className="flex-1">
                            <label className="block text-xs text-slate-500 mb-1">
                              {t.to}
                            </label>
                            <input
                              type="time"
                              value={
                                (config.workingHours as Record<string, string>)
                                  ?.end || "17:00"
                              }
                              onChange={(e) =>
                                updateWorkingHours("end", e.target.value)
                              }
                              className="w-full px-3 py-2 rounded-lg border border-slate-300 text-slate-900 focus:border-brand-green focus:ring-2 focus:ring-brand-green/25 focus:outline-none"
                            />
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Language Section */}
                    <div className="space-y-4">
                      <h3 className="flex items-center gap-2 text-sm font-semibold text-slate-700 uppercase tracking-wide">
                        <Globe className="h-4 w-4" />
                        {t.language}
                      </h3>

                      <div className="p-4 rounded-xl bg-slate-50 border border-slate-200">
                        <div className="flex items-center gap-3 mb-3">
                          <Globe className="h-5 w-5 text-slate-500" />
                          <div>
                            <p className="font-medium text-slate-900">
                              {t.responseLanguage}
                            </p>
                            <p className="text-sm text-slate-500">
                              {t.responseLanguageDesc}
                            </p>
                          </div>
                        </div>
                        <div className="grid grid-cols-3 gap-2">
                          {[
                            { value: "ar", label: t.arabic },
                            { value: "en", label: t.english },
                            { value: "both", label: t.both },
                          ].map((option) => (
                            <button
                              key={option.value}
                              onClick={() =>
                                updateConfig("language", option.value)
                              }
                              className={`p-3 rounded-lg font-medium text-sm transition-all ${
                                config.language === option.value
                                  ? "bg-brand-green text-white"
                                  : "bg-white border border-slate-200 text-slate-600 hover:border-brand-green"
                              }`}
                            >
                              {option.label}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>

              {/* Footer */}
              <div className="flex items-center justify-end gap-3 p-6 border-t border-slate-200 bg-slate-50">
                <button
                  onClick={onClose}
                  disabled={saving}
                  className="px-4 py-2 rounded-lg font-medium text-slate-600 hover:bg-slate-200 transition-colors disabled:opacity-50"
                >
                  {t.cancel}
                </button>
                <button
                  onClick={handleSave}
                  disabled={saving || loading}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-lg font-medium text-white bg-brand-green hover:bg-brand-greenHover transition-colors disabled:opacity-50"
                >
                  {saving ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      {t.saving}
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4" />
                      {t.save}
                    </>
                  )}
                </button>
              </div>
            </Dialog.Panel>
          </Transition.Child>
        </div>
      </Dialog>
    </Transition>
  );
}
