/**
 * Sector Picker Form
 *
 * Lets organization owners pick their industry from the dashboard. On
 * save, sets industry/sector + reseeds sector-specific workflows so the
 * AI engine starts using sector-appropriate vocabulary (e.g. "viewing"
 * for property, "reservation" for restaurants) immediately.
 *
 * Renders inside the WhatsApp setup wizard right after credentials are
 * saved (Meta or Twilio path), and is also available as a standalone
 * panel in the dashboard so owners can change their sector later.
 */

"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import {
  Loader2,
  AlertCircle,
  CheckCircle2,
  Building2,
  Sparkles,
} from "lucide-react";
import type { Lang } from "@/lib/config";
import { useOrganizationRole } from "@/components/dashboard/hooks/useOrganizationRole";
import {
  INDUSTRY_TO_SECTOR,
  SECTOR_DISPLAY_NAMES,
  type SectorKey,
} from "@/lib/config/industry-sector-map";

interface SectorPickerFormProps {
  lang: Lang;
  onSuccess?: () => void;
  onSkip?: () => void;
  showSkip?: boolean;
}

interface ServerState {
  industry: string | null;
  sector: string | null;
  activeWorkflowCount: number;
}

// Bilingual labels for each industry key
const INDUSTRY_LABELS: Record<string, { en: string; ar: string }> = {
  // Health & Care
  healthcare: { en: "Healthcare / Clinic", ar: "رعاية صحية / عيادة" },
  dental: { en: "Dental", ar: "أسنان" },
  physio: { en: "Physiotherapy", ar: "علاج طبيعي" },
  "labs-diagnostics": { en: "Labs & Diagnostics", ar: "مختبرات وتشخيص" },
  telehealth: { en: "Telehealth", ar: "صحة عن بعد" },
  optometry: { en: "Optometry", ar: "بصريات" },
  pharmacy: { en: "Pharmacy", ar: "صيدلية" },
  // Beauty & Wellness
  "beauty-wellness": { en: "Beauty & Wellness", ar: "الجمال والعافية" },
  aesthetics: { en: "Aesthetics", ar: "تجميل" },
  "medical-spas": { en: "Medical Spa", ar: "سبا طبي" },
  // Food, Hospitality & Stays
  "food-hospitality": { en: "Food & Hospitality", ar: "أطعمة وضيافة" },
  "restaurants-cafes": { en: "Restaurant / Café", ar: "مطعم / كافيه" },
  "hotels-accommodation": { en: "Hotel / Accommodation", ar: "فندق / إقامة" },
  // Retail & Services
  "retail-services": { en: "Retail / Services", ar: "تجزئة / خدمات" },
  other: { en: "Other", ar: "أخرى" },
  // Property & Facilities
  "property-facilities": {
    en: "Property / Real Estate",
    ar: "عقارات / مرافق",
  },
  // Mobility & Automotive
  "mobility-industry": { en: "Mobility / Transport", ar: "تنقل / نقل" },
  "vehicle-rental": { en: "Vehicle Rental", ar: "تأجير مركبات" },
  // Home Services & Trades
  "home-services-trades": {
    en: "Home Services / Trades",
    ar: "خدمات منزلية / حرف",
  },
  // Education
  education: { en: "Education", ar: "تعليم" },
  "sports-academies": { en: "Sports Academy", ar: "أكاديمية رياضية" },
  // Events & Venues
  "events-venues": { en: "Events & Venues", ar: "فعاليات وأماكن" },
  // Pet Services
  "pet-services": { en: "Pet Services", ar: "خدمات حيوانات أليفة" },
  vet: { en: "Veterinary", ar: "بيطري" },
  // Nonprofit & Community
  "nonprofit-community": {
    en: "Nonprofit / Community",
    ar: "غير ربحي / مجتمعي",
  },
  // Public Sector
  "public-sector": { en: "Public Sector", ar: "قطاع عام" },
};

export default function SectorPickerForm({
  lang,
  onSuccess,
  onSkip,
  showSkip = false,
}: SectorPickerFormProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";
  const { organizationId } = useOrganizationRole();

  const [csrfToken, setCsrfToken] = useState("");
  const [server, setServer] = useState<ServerState | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedIndustry, setSelectedIndustry] = useState("");
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [savedResult, setSavedResult] = useState<{
    seeded: number;
    sectorLabel: string;
  } | null>(null);

  const t = {
    title: isAr ? "حدد مجال نشاط الشركة" : "What kind of business is this?",
    subtitle: isAr
      ? "نستخدم هذا لتفعيل سير العمل والكلمات المناسبة لقطاعك"
      : "We use this to activate the right workflows and vocabulary for your sector",
    industryLabel: isAr ? "اختر مجال نشاطك" : "Pick your industry",
    save: isAr ? "حفظ وتفعيل سير العمل" : "Save & activate workflows",
    saving: isAr ? "جارٍ الحفظ..." : "Saving...",
    skip: isAr ? "تخطي الآن" : "Skip for now",
    successTitle: isAr ? "تم تفعيل سير العمل" : "Workflows activated",
    successCount: isAr
      ? "{n} سير عمل نشط لـ {sector}"
      : "{n} workflows now active for {sector}",
    activeNow: isAr ? "نشط حالياً" : "Currently active",
    workflows: isAr ? "سير عمل" : "workflows",
    forSector: isAr ? "لقطاع" : "for",
    none: isAr ? "لم يتم اختيار قطاع بعد" : "No sector selected yet",
    loadingMsg: isAr ? "جارٍ التحميل..." : "Loading...",
    selectPrompt: isAr ? "-- اختر --" : "-- Select --",
  };

  // Group industries by sector for the dropdown
  const groupedIndustries = useMemo(() => {
    const groups: Record<SectorKey, Array<{ key: string; label: string }>> =
      {} as Record<SectorKey, Array<{ key: string; label: string }>>;

    for (const [industry, sector] of Object.entries(INDUSTRY_TO_SECTOR)) {
      if (!groups[sector]) groups[sector] = [];
      const label = INDUSTRY_LABELS[industry]?.[isAr ? "ar" : "en"] ?? industry;
      groups[sector].push({ key: industry, label });
    }
    return groups;
  }, [isAr]);

  // Fetch CSRF token
  useEffect(() => {
    fetch("/api/csrf")
      .then((r) => r.json())
      .then((j) => {
        if (j?.csrfToken) setCsrfToken(j.csrfToken as string);
      })
      .catch(() => {
        /* non-fatal */
      });
  }, []);

  // Load current sector config
  const loadConfig = useCallback(async () => {
    if (!organizationId) return;
    setLoading(true);
    try {
      const res = await fetch(
        `/api/dashboard/sector-config?organizationId=${encodeURIComponent(organizationId)}`,
        { credentials: "include" },
      );
      const data = await res.json();
      if (res.ok && data.success !== false) {
        setServer({
          industry: data.industry ?? null,
          sector: data.sector ?? null,
          activeWorkflowCount: Number(data.activeWorkflowCount ?? 0),
        });
        if (data.industry) setSelectedIndustry(data.industry);
      }
    } catch {
      /* non-fatal */
    } finally {
      setLoading(false);
    }
  }, [organizationId]);

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

  const handleSave = async () => {
    setError("");
    setSavedResult(null);

    if (!organizationId) {
      setError(
        isAr ? "لم نجد منظمة لربطها" : "No organization found",
      );
      return;
    }
    if (!selectedIndustry) {
      setError(isAr ? "اختر مجال نشاطك" : "Pick an industry");
      return;
    }

    setSaving(true);
    try {
      const res = await fetch("/api/dashboard/sector-config", {
        method: "PATCH",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          organizationId,
          industry: selectedIndustry,
        }),
      });

      const data = await res.json();
      if (!res.ok || data.success === false) {
        setError(data.error || (isAr ? "فشل الحفظ" : "Save failed"));
        return;
      }

      const sectorKey = data.sector as SectorKey;
      const sectorLabel =
        SECTOR_DISPLAY_NAMES[sectorKey]?.[isAr ? "ar" : "en"] ?? sectorKey;

      setSavedResult({
        seeded: Number(data.seededWorkflows ?? 0),
        sectorLabel,
      });
      setServer({
        industry: data.industry,
        sector: data.sector,
        activeWorkflowCount: Number(data.activeWorkflowCount ?? 0),
      });

      // Auto-advance to next stage after a moment so the user sees
      // the success state
      if (onSuccess) {
        setTimeout(() => onSuccess(), 1500);
      }
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "خطأ غير متوقع"
            : "Unexpected error",
      );
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div
        dir={dir}
        className="rounded-xl bg-white shadow-sm p-12 flex items-center justify-center text-slate-500"
      >
        <Loader2 className="w-5 h-5 animate-spin mr-2" />
        {t.loadingMsg}
      </div>
    );
  }

  return (
    <div className="rounded-xl bg-white shadow-sm p-8" dir={dir}>
      <div className="max-w-2xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-emerald-100 flex items-center justify-center">
            <Building2 className="w-8 h-8 text-emerald-600" />
          </div>
          <h2 className="text-2xl font-bold text-slate-900 mb-2">{t.title}</h2>
          <p className="text-slate-600">{t.subtitle}</p>
        </div>

        {/* Current state — show if already configured */}
        {server?.industry && !savedResult && (
          <div className="mb-6 rounded-xl border border-emerald-200 bg-emerald-50 p-4 flex items-center gap-3">
            <Sparkles className="w-5 h-5 text-emerald-600 flex-shrink-0" />
            <div className="flex-1 text-sm">
              <span className="font-medium text-emerald-900">
                {t.activeNow}:
              </span>{" "}
              <span className="text-emerald-700">
                {server.activeWorkflowCount} {t.workflows} {t.forSector}{" "}
                <strong>
                  {SECTOR_DISPLAY_NAMES[server.sector as SectorKey]?.[
                    isAr ? "ar" : "en"
                  ] ?? server.sector}
                </strong>
              </span>
            </div>
          </div>
        )}

        {/* Industry dropdown */}
        <div className="mb-6">
          <label className="block text-sm font-medium text-slate-900 mb-2">
            {t.industryLabel}
          </label>
          <select
            value={selectedIndustry}
            onChange={(e) => setSelectedIndustry(e.target.value)}
            disabled={saving}
            dir={dir}
            className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-base text-slate-900 focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 focus:outline-none transition-all disabled:opacity-50"
          >
            <option value="">{t.selectPrompt}</option>
            {Object.entries(groupedIndustries).map(([sectorKey, items]) => (
              <optgroup
                key={sectorKey}
                label={
                  SECTOR_DISPLAY_NAMES[sectorKey as SectorKey]?.[
                    isAr ? "ar" : "en"
                  ] ?? sectorKey
                }
              >
                {items.map((item) => (
                  <option key={item.key} value={item.key}>
                    {item.label}
                  </option>
                ))}
              </optgroup>
            ))}
          </select>
        </div>

        {/* Success message */}
        {savedResult && (
          <div className="mb-6 rounded-xl border-2 border-emerald-300 bg-emerald-50 p-4 flex items-start gap-3">
            <CheckCircle2 className="w-5 h-5 text-emerald-600 flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <div className="text-sm font-semibold text-emerald-900 mb-1">
                {t.successTitle}
              </div>
              <div className="text-sm text-emerald-700">
                {t.successCount
                  .replace("{n}", String(savedResult.seeded))
                  .replace("{sector}", savedResult.sectorLabel)}
              </div>
            </div>
          </div>
        )}

        {/* Error */}
        {error && (
          <div className="mb-6 flex items-start gap-2 rounded-xl bg-rose-50 border border-rose-200 px-4 py-3">
            <AlertCircle className="w-4 h-4 text-rose-600 flex-shrink-0 mt-0.5" />
            <span className="text-sm text-rose-700">{error}</span>
          </div>
        )}

        {/* Actions */}
        <div
          className={`flex items-center ${showSkip ? "justify-between" : "justify-end"} gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          {showSkip && onSkip && (
            <button
              type="button"
              onClick={onSkip}
              disabled={saving}
              className="px-5 py-2.5 text-slate-600 hover:text-slate-900 font-medium transition-colors disabled:opacity-50"
            >
              {t.skip}
            </button>
          )}

          <button
            type="button"
            onClick={handleSave}
            disabled={saving || !selectedIndustry || !organizationId}
            className="inline-flex items-center gap-2 px-6 py-2.5 bg-emerald-600 text-white font-semibold rounded-xl hover:bg-emerald-700 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {saving && <Loader2 className="w-4 h-4 animate-spin" />}
            {saving ? t.saving : t.save}
          </button>
        </div>
      </div>
    </div>
  );
}
