/**
 * Brokers Panel Component
 * Broker management with cards showing stats, specializations, and active/inactive toggle
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import dynamic from "next/dynamic";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Plus,
  Loader2,
  Phone,
  Mail,
  Eye,
  TrendingUp,
  UserCircle,
  RefreshCw,
  ToggleLeft,
  ToggleRight,
  Upload,
} from "lucide-react";

const BrokerProfileModal = dynamic(() => import("./BrokerProfileModal"), {
  ssr: false,
});
const RealEstateBulkImportModal = dynamic(
  () => import("./RealEstateBulkImportModal"),
  { ssr: false },
);

export interface Broker {
  id: string;
  nameEn: string;
  nameAr: string;
  phone: string;
  email?: string;
  whatsapp?: string;
  photo?: string;
  languages: string[];
  areaSpecializations: string[];
  typeSpecializations: string[];
  isActive: boolean;
  stats?: {
    totalViewings: number;
    completedViewings: number;
    conversionRate: number;
  };
  schedule?: {
    workingDays: string[];
    startTime: string;
    endTime: string;
    maxViewingsPerDay: number;
  };
}

interface BrokersPanelProps {
  lang: Lang;
}

export default function BrokersPanel({ lang }: BrokersPanelProps) {
  const isAr = lang === "ar";

  const [brokers, setBrokers] = useState<Broker[]>([]);
  const [loading, setLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showProfileModal, setShowProfileModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [selectedBroker, setSelectedBroker] = useState<Broker | null>(null);
  const [togglingId, setTogglingId] = useState<string | null>(null);

  const fetchBrokers = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/real-estate/brokers");
      const data = await res.json();
      if (data.success) {
        setBrokers(data.brokers || []);
      }
    } catch (error) {
      console.error("Failed to fetch brokers:", error);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await fetchBrokers();
    setTimeout(() => setIsRefreshing(false), 500);
  };

  const handleToggleActive = async (broker: Broker) => {
    setTogglingId(broker.id);
    try {
      const res = await fetchWithCSRF(
        `/api/real-estate/brokers/${broker.id}/toggle`,
        {
          method: "PATCH",
          body: JSON.stringify({ isActive: !broker.isActive }),
        },
      );
      const data = await res.json();
      if (data.success) {
        setBrokers((prev) =>
          prev.map((b) =>
            b.id === broker.id ? { ...b, isActive: !b.isActive } : b,
          ),
        );
      }
    } catch (error) {
      console.error("Failed to toggle broker:", error);
    } finally {
      setTogglingId(null);
    }
  };

  const handleEditBroker = (broker: Broker) => {
    setSelectedBroker(broker);
    setShowProfileModal(true);
  };

  const handleAddBroker = () => {
    setSelectedBroker(null);
    setShowProfileModal(true);
  };

  const handleBrokerSaved = () => {
    setShowProfileModal(false);
    setSelectedBroker(null);
    fetchBrokers();
  };

  return (
    <>
      <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
        {/* Header */}
        <div className="border-b border-slate-100 p-5">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <div className="flex items-center gap-3">
                <h2 className="text-lg font-bold text-slate-900">
                  {isAr ? "الوسطاء" : "Brokers"}
                </h2>
                <button
                  onClick={handleRefresh}
                  disabled={isRefreshing}
                  className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 px-2.5 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 transition-all disabled:opacity-50"
                >
                  <RefreshCw
                    className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
                  />
                </button>
                <span className="text-xs text-slate-400">
                  ({brokers.length} {isAr ? "وسيط" : "brokers"})
                </span>
              </div>
              <p className="text-sm text-slate-500 mt-0.5">
                {isAr
                  ? "إدارة فريق الوسطاء العقاريين"
                  : "Manage your real estate broker team"}
              </p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowImportModal(true)}
                className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
              >
                <Upload className="w-4 h-4" />
                {isAr ? "استيراد CSV" : "Import CSV"}
              </button>
              <button
                onClick={handleAddBroker}
                className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
              >
                <Plus className="w-4 h-4" />
                {isAr ? "إضافة وسيط" : "Add Broker"}
              </button>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-5">
          {loading ? (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
            </div>
          ) : brokers.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
                <UserCircle className="w-8 h-8 text-slate-400" />
              </div>
              <p className="text-sm font-medium text-slate-600">
                {isAr ? "لا يوجد وسطاء بعد" : "No brokers yet"}
              </p>
              <p className="mt-1 text-xs text-slate-400 max-w-[250px]">
                {isAr
                  ? "أضف أول وسيط لبدء إدارة المعاينات"
                  : "Add your first broker to start managing viewings"}
              </p>
              <button
                onClick={handleAddBroker}
                className="mt-4 inline-flex items-center gap-2 rounded-lg bg-brand-green px-4 py-2 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
              >
                <Plus className="w-4 h-4" />
                {isAr ? "إضافة وسيط" : "Add Broker"}
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {brokers.map((broker) => (
                <div
                  key={broker.id}
                  className={`group rounded-xl border-2 ${
                    broker.isActive
                      ? "border-slate-200"
                      : "border-slate-200 opacity-60"
                  } bg-white overflow-hidden transition-all hover:border-brand-green hover:shadow-lg`}
                >
                  {/* Card Header */}
                  <div className="p-4">
                    <div className="flex items-start justify-between">
                      <div
                        className="flex items-center gap-3 cursor-pointer"
                        onClick={() => handleEditBroker(broker)}
                      >
                        {broker.photo ? (
                          <img
                            src={broker.photo}
                            alt={isAr ? broker.nameAr : broker.nameEn}
                            className="w-12 h-12 rounded-full object-cover border-2 border-slate-200"
                          />
                        ) : (
                          <div className="w-12 h-12 rounded-full bg-gradient-to-br from-brand-green/20 to-emerald-500/20 flex items-center justify-center border-2 border-emerald-200">
                            <span className="text-lg font-bold text-brand-green">
                              {(isAr ? broker.nameAr : broker.nameEn)
                                .charAt(0)
                                .toUpperCase()}
                            </span>
                          </div>
                        )}
                        <div>
                          <h3 className="text-sm font-bold text-slate-900">
                            {isAr ? broker.nameAr : broker.nameEn}
                          </h3>
                          <div className="flex items-center gap-2 mt-0.5">
                            <span
                              className={`inline-flex rounded-full px-2 py-0.5 text-[10px] font-semibold ${
                                broker.isActive
                                  ? "bg-emerald-100 text-emerald-700"
                                  : "bg-slate-100 text-slate-500"
                              }`}
                            >
                              {broker.isActive
                                ? isAr
                                  ? "نشط"
                                  : "Active"
                                : isAr
                                  ? "غير نشط"
                                  : "Inactive"}
                            </span>
                          </div>
                        </div>
                      </div>
                      <button
                        onClick={() => handleToggleActive(broker)}
                        disabled={togglingId === broker.id}
                        className="text-slate-400 hover:text-brand-green transition-colors disabled:opacity-50"
                        title={
                          broker.isActive
                            ? isAr
                              ? "إيقاف"
                              : "Deactivate"
                            : isAr
                              ? "تفعيل"
                              : "Activate"
                        }
                      >
                        {togglingId === broker.id ? (
                          <Loader2 className="w-5 h-5 animate-spin" />
                        ) : broker.isActive ? (
                          <ToggleRight className="w-6 h-6 text-brand-green" />
                        ) : (
                          <ToggleLeft className="w-6 h-6" />
                        )}
                      </button>
                    </div>

                    {/* Contact Info */}
                    <div className="mt-3 space-y-1">
                      <div className="flex items-center gap-2 text-xs text-slate-500">
                        <Phone className="w-3 h-3" />
                        <span dir="ltr">{broker.phone}</span>
                      </div>
                      {broker.email && (
                        <div className="flex items-center gap-2 text-xs text-slate-500">
                          <Mail className="w-3 h-3" />
                          <span className="truncate">{broker.email}</span>
                        </div>
                      )}
                    </div>

                    {/* Specializations */}
                    {broker.typeSpecializations.length > 0 && (
                      <div className="mt-3 flex flex-wrap gap-1">
                        {broker.typeSpecializations.slice(0, 3).map((spec) => (
                          <span
                            key={spec}
                            className="rounded-md bg-blue-50 px-2 py-0.5 text-[10px] font-medium text-blue-700"
                          >
                            {spec}
                          </span>
                        ))}
                        {broker.typeSpecializations.length > 3 && (
                          <span className="text-[10px] text-slate-400">
                            +{broker.typeSpecializations.length - 3}
                          </span>
                        )}
                      </div>
                    )}
                  </div>

                  {/* Stats */}
                  {broker.stats && (
                    <div className="border-t border-slate-100 px-4 py-3 grid grid-cols-3 gap-2">
                      <div className="text-center">
                        <div className="flex items-center justify-center gap-1">
                          <Eye className="w-3 h-3 text-slate-400" />
                          <p className="text-sm font-bold text-slate-700">
                            {broker.stats.totalViewings}
                          </p>
                        </div>
                        <p className="text-[10px] text-slate-500">
                          {isAr ? "معاينات" : "Viewings"}
                        </p>
                      </div>
                      <div className="text-center">
                        <div className="flex items-center justify-center gap-1">
                          <TrendingUp className="w-3 h-3 text-emerald-500" />
                          <p className="text-sm font-bold text-emerald-600">
                            {broker.stats.conversionRate}%
                          </p>
                        </div>
                        <p className="text-[10px] text-slate-500">
                          {isAr ? "تحويل" : "Convert"}
                        </p>
                      </div>
                      <div className="text-center">
                        <p className="text-sm font-bold text-slate-700">
                          {broker.stats.completedViewings}
                        </p>
                        <p className="text-[10px] text-slate-500">
                          {isAr ? "مكتمل" : "Completed"}
                        </p>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Bulk Import Modal */}
      <RealEstateBulkImportModal
        lang={lang}
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        onImportComplete={() => {
          fetchBrokers();
          setShowImportModal(false);
        }}
        initialEntityType="brokers"
      />

      {/* Broker Profile Modal */}
      <BrokerProfileModal
        lang={lang}
        isOpen={showProfileModal}
        onClose={() => {
          setShowProfileModal(false);
          setSelectedBroker(null);
        }}
        onSuccess={handleBrokerSaved}
        broker={selectedBroker}
      />
    </>
  );
}
