/**
 * Properties Panel Component
 * Main property management panel with list/grid view, filters, search, and pagination
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import dynamic from "next/dynamic";
import type { Lang } from "@/lib/config";
import {
  Search,
  Plus,
  Filter,
  LayoutGrid,
  List,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Building2,
  BedDouble,
  Bath,
  Maximize2,
  MapPin,
  RefreshCw,
  Upload,
} from "lucide-react";

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

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface Property {
  id: string;
  titleEn: string;
  titleAr: string;
  descriptionEn?: string;
  descriptionAr?: string;
  propertyType: string;
  listingType: string;
  status: string;
  bedrooms?: number;
  bathrooms?: number;
  area?: number;
  floor?: number;
  price: number;
  currency: string;
  negotiable?: boolean;
  country: string;
  city: string;
  district?: string;
  building?: string;
  unit?: string;
  furnishing?: string;
  ownership?: string;
  amenities?: string[];
  images?: string[];
  createdAt: string;
  updatedAt: string;
}

interface PropertiesPanelProps {
  lang: Lang;
}

const PROPERTY_TYPES = [
  { value: "", labelEn: "All Types", labelAr: "جميع الأنواع" },
  { value: "apartment", labelEn: "Apartment", labelAr: "شقة" },
  { value: "villa", labelEn: "Villa", labelAr: "فيلا" },
  { value: "townhouse", labelEn: "Townhouse", labelAr: "تاون هاوس" },
  { value: "penthouse", labelEn: "Penthouse", labelAr: "بنتهاوس" },
  { value: "studio", labelEn: "Studio", labelAr: "استوديو" },
  { value: "office", labelEn: "Office", labelAr: "مكتب" },
  { value: "retail", labelEn: "Retail", labelAr: "تجاري" },
  { value: "warehouse", labelEn: "Warehouse", labelAr: "مستودع" },
  { value: "land", labelEn: "Land", labelAr: "أرض" },
];

const STATUS_OPTIONS = [
  { value: "", labelEn: "All Statuses", labelAr: "جميع الحالات" },
  { value: "available", labelEn: "Available", labelAr: "متاح" },
  { value: "reserved", labelEn: "Reserved", labelAr: "محجوز" },
  { value: "sold", labelEn: "Sold", labelAr: "مباع" },
  { value: "rented", labelEn: "Rented", labelAr: "مؤجر" },
  { value: "off_market", labelEn: "Off Market", labelAr: "خارج السوق" },
];

const PAGE_SIZE = 12;

export default function PropertiesPanel({ lang }: PropertiesPanelProps) {
  const isAr = lang === "ar";

  // Data
  const [properties, setProperties] = useState<Property[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(true);

  // Filters
  const [search, setSearch] = useState("");
  const [filterType, setFilterType] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  const [priceMin, setPriceMin] = useState("");
  const [priceMax, setPriceMax] = useState("");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [page, setPage] = useState(1);

  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [selectedProperty, setSelectedProperty] = useState<Property | null>(
    null,
  );
  const [showDetailModal, setShowDetailModal] = useState(false);

  // Refresh
  const [isRefreshing, setIsRefreshing] = useState(false);

  const totalPages = Math.ceil(totalCount / PAGE_SIZE);

  const fetchProperties = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      params.set("page", String(page));
      params.set("limit", String(PAGE_SIZE));
      if (search) params.set("search", search);
      if (filterType) params.set("type", filterType);
      if (filterStatus) params.set("status", filterStatus);
      if (priceMin) params.set("priceMin", priceMin);
      if (priceMax) params.set("priceMax", priceMax);

      const res = await fetch(
        `/api/real-estate/properties?${params.toString()}`,
      );
      const data = await res.json();
      if (data.success) {
        setProperties(data.properties || []);
        setTotalCount(data.total || 0);
      }
    } catch (error) {
      console.error("Failed to fetch properties:", error);
    } finally {
      setLoading(false);
    }
  }, [page, search, filterType, filterStatus, priceMin, priceMax]);

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

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

  const handlePropertyCreated = () => {
    setShowCreateModal(false);
    setPage(1);
    fetchProperties();
  };

  const handleViewProperty = (property: Property) => {
    setSelectedProperty(property);
    setShowDetailModal(true);
  };

  const getStatusBadge = (status: string) => {
    const badges: Record<
      string,
      { bg: string; text: string; labelEn: string; labelAr: string }
    > = {
      available: {
        bg: "bg-emerald-100",
        text: "text-emerald-700",
        labelEn: "Available",
        labelAr: "متاح",
      },
      reserved: {
        bg: "bg-amber-100",
        text: "text-amber-700",
        labelEn: "Reserved",
        labelAr: "محجوز",
      },
      sold: {
        bg: "bg-blue-100",
        text: "text-blue-700",
        labelEn: "Sold",
        labelAr: "مباع",
      },
      rented: {
        bg: "bg-violet-100",
        text: "text-violet-700",
        labelEn: "Rented",
        labelAr: "مؤجر",
      },
      off_market: {
        bg: "bg-slate-100",
        text: "text-slate-600",
        labelEn: "Off Market",
        labelAr: "خارج السوق",
      },
    };
    const badge = badges[status] || badges.available;
    return (
      <span
        className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${badge.bg} ${badge.text}`}
      >
        {isAr ? badge.labelAr : badge.labelEn}
      </span>
    );
  };

  const formatPrice = (price: number, currency: string) => {
    return (
      new Intl.NumberFormat(isAr ? "ar-SA" : "en-US", {
        style: "decimal",
        maximumFractionDigits: 0,
      }).format(price) + ` ${currency}`
    );
  };

  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 ? "العقارات" : "Properties"}
                </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 hover:border-slate-300 transition-all disabled:opacity-50"
                >
                  <RefreshCw
                    className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
                  />
                </button>
                <span className="text-xs text-slate-400">
                  ({totalCount} {isAr ? "عقار" : "properties"})
                </span>
              </div>
              <p className="text-sm text-slate-500 mt-0.5">
                {isAr
                  ? "إدارة قوائم العقارات الخاصة بك"
                  : "Manage your property listings"}
              </p>
            </div>
            <div className="flex items-center gap-2">
              {/* View Toggle */}
              <div className="flex items-center rounded-lg border border-slate-200 overflow-hidden">
                <button
                  onClick={() => setViewMode("grid")}
                  className={`p-2 transition-colors ${viewMode === "grid" ? "bg-brand-green text-white" : "bg-white text-slate-500 hover:bg-slate-50"}`}
                >
                  <LayoutGrid className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setViewMode("list")}
                  className={`p-2 transition-colors ${viewMode === "list" ? "bg-brand-green text-white" : "bg-white text-slate-500 hover:bg-slate-50"}`}
                >
                  <List className="w-4 h-4" />
                </button>
              </div>
              <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" />
                <span className="hidden sm:inline">
                  {isAr ? "استيراد CSV" : "Import CSV"}
                </span>
              </button>
              <button
                onClick={() => setShowCreateModal(true)}
                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" />
                <span className="hidden sm:inline">
                  {isAr ? "إضافة عقار" : "Add Property"}
                </span>
              </button>
            </div>
          </div>

          {/* Search & Filters */}
          <div className="mt-4 flex flex-wrap gap-3">
            {/* Search */}
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
              <input
                type="text"
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
                placeholder={isAr ? "ابحث عن عقار..." : "Search properties..."}
                className="w-full rounded-xl border border-slate-200 bg-slate-50 pl-9 pr-4 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
              />
            </div>

            {/* Type Filter */}
            <div className="relative">
              <Filter className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
              <select
                value={filterType}
                onChange={(e) => {
                  setFilterType(e.target.value);
                  setPage(1);
                }}
                className="appearance-none rounded-xl border border-slate-200 bg-slate-50 pl-9 pr-8 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
              >
                {PROPERTY_TYPES.map((t) => (
                  <option key={t.value} value={t.value}>
                    {isAr ? t.labelAr : t.labelEn}
                  </option>
                ))}
              </select>
            </div>

            {/* Status Filter */}
            <select
              value={filterStatus}
              onChange={(e) => {
                setFilterStatus(e.target.value);
                setPage(1);
              }}
              className="appearance-none rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
            >
              {STATUS_OPTIONS.map((s) => (
                <option key={s.value} value={s.value}>
                  {isAr ? s.labelAr : s.labelEn}
                </option>
              ))}
            </select>

            {/* Price Range */}
            <input
              type="number"
              value={priceMin}
              onChange={(e) => {
                setPriceMin(e.target.value);
                setPage(1);
              }}
              placeholder={isAr ? "السعر من" : "Price min"}
              className="w-28 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
              dir="ltr"
            />
            <input
              type="number"
              value={priceMax}
              onChange={(e) => {
                setPriceMax(e.target.value);
                setPage(1);
              }}
              placeholder={isAr ? "السعر إلى" : "Price max"}
              className="w-28 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2.5 text-sm font-medium text-slate-700 focus:border-brand-green focus:bg-white focus:outline-none focus:ring-2 focus:ring-brand-green/20 transition-all"
              dir="ltr"
            />
          </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>
          ) : properties.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">
                <Building2 className="w-8 h-8 text-slate-400" />
              </div>
              <p className="text-sm font-medium text-slate-600">
                {isAr ? "لا توجد عقارات بعد" : "No properties yet"}
              </p>
              <p className="mt-1 text-xs text-slate-400 max-w-[250px]">
                {isAr
                  ? "أضف أول عقار لبدء الإدارة"
                  : "Add your first property to get started"}
              </p>
              <button
                onClick={() => setShowCreateModal(true)}
                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 Property"}
              </button>
            </div>
          ) : viewMode === "grid" ? (
            /* Grid View */
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {properties.map((property) => (
                <div
                  key={property.id}
                  onClick={() => handleViewProperty(property)}
                  className="group rounded-xl border border-slate-200 bg-white overflow-hidden cursor-pointer transition-all hover:border-brand-green hover:shadow-lg hover:-translate-y-0.5"
                >
                  {/* Image */}
                  <div className="relative h-48 bg-slate-100">
                    {property.images && property.images.length > 0 ? (
                      <img
                        src={property.images[0]}
                        alt={isAr ? property.titleAr : property.titleEn}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <Building2 className="w-12 h-12 text-slate-300" />
                      </div>
                    )}
                    <div className="absolute top-3 left-3">
                      {getStatusBadge(property.status)}
                    </div>
                    <div className="absolute top-3 right-3">
                      <span className="inline-flex rounded-full bg-white/90 backdrop-blur-sm px-2 py-0.5 text-xs font-semibold text-slate-700">
                        {property.listingType === "sale"
                          ? isAr
                            ? "للبيع"
                            : "Sale"
                          : isAr
                            ? "للإيجار"
                            : "Rent"}
                      </span>
                    </div>
                  </div>

                  {/* Content */}
                  <div className="p-4">
                    <h3 className="text-sm font-bold text-slate-900 line-clamp-1">
                      {isAr ? property.titleAr : property.titleEn}
                    </h3>
                    <div className="flex items-center gap-1 mt-1 text-xs text-slate-500">
                      <MapPin className="w-3 h-3" />
                      <span className="line-clamp-1">
                        {property.district ? `${property.district}, ` : ""}
                        {property.city}
                      </span>
                    </div>

                    <p className="mt-2 text-lg font-bold text-brand-green">
                      {formatPrice(property.price, property.currency)}
                    </p>

                    {/* Specs */}
                    <div className="mt-3 flex items-center gap-3 text-xs text-slate-500">
                      {property.bedrooms != null && (
                        <span className="flex items-center gap-1">
                          <BedDouble className="w-3.5 h-3.5" />
                          {property.bedrooms}
                        </span>
                      )}
                      {property.bathrooms != null && (
                        <span className="flex items-center gap-1">
                          <Bath className="w-3.5 h-3.5" />
                          {property.bathrooms}
                        </span>
                      )}
                      {property.area != null && (
                        <span className="flex items-center gap-1">
                          <Maximize2 className="w-3.5 h-3.5" />
                          {property.area} m²
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            /* List View */
            <div className="space-y-3">
              {properties.map((property) => (
                <div
                  key={property.id}
                  onClick={() => handleViewProperty(property)}
                  className="group flex items-center gap-4 rounded-xl border border-slate-200 bg-slate-50/50 p-4 cursor-pointer transition-all hover:border-brand-green hover:bg-white hover:shadow-md"
                >
                  {/* Thumbnail */}
                  <div className="w-20 h-20 rounded-lg bg-slate-100 overflow-hidden shrink-0">
                    {property.images && property.images.length > 0 ? (
                      <img
                        src={property.images[0]}
                        alt={isAr ? property.titleAr : property.titleEn}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <Building2 className="w-6 h-6 text-slate-300" />
                      </div>
                    )}
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <h3 className="text-sm font-bold text-slate-900 truncate">
                        {isAr ? property.titleAr : property.titleEn}
                      </h3>
                      {getStatusBadge(property.status)}
                    </div>
                    <div className="flex items-center gap-1 mt-0.5 text-xs text-slate-500">
                      <MapPin className="w-3 h-3" />
                      <span>
                        {property.district ? `${property.district}, ` : ""}
                        {property.city}
                      </span>
                    </div>
                    <div className="mt-1 flex items-center gap-3 text-xs text-slate-500">
                      {property.bedrooms != null && (
                        <span className="flex items-center gap-1">
                          <BedDouble className="w-3.5 h-3.5" />{" "}
                          {property.bedrooms} {isAr ? "غرف" : "beds"}
                        </span>
                      )}
                      {property.bathrooms != null && (
                        <span className="flex items-center gap-1">
                          <Bath className="w-3.5 h-3.5" /> {property.bathrooms}{" "}
                          {isAr ? "حمامات" : "baths"}
                        </span>
                      )}
                      {property.area != null && (
                        <span className="flex items-center gap-1">
                          <Maximize2 className="w-3.5 h-3.5" /> {property.area}{" "}
                          m²
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Price */}
                  <div className="text-right shrink-0">
                    <p className="text-lg font-bold text-brand-green">
                      {formatPrice(property.price, property.currency)}
                    </p>
                    <p className="text-xs text-slate-400">
                      {property.listingType === "sale"
                        ? isAr
                          ? "للبيع"
                          : "For Sale"
                        : isAr
                          ? "للإيجار"
                          : "For Rent"}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="mt-6 flex items-center justify-between">
              <p className="text-xs text-slate-500">
                {isAr
                  ? `صفحة ${page} من ${totalPages}`
                  : `Page ${page} of ${totalPages}`}
              </p>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:border-brand-green transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="w-3.5 h-3.5" />
                  {isAr ? "السابق" : "Prev"}
                </button>
                <button
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages}
                  className="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-medium text-slate-700 hover:border-brand-green transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isAr ? "التالي" : "Next"}
                  <ChevronRight className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Create Property Modal */}
      <CreatePropertyModal
        lang={lang}
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={handlePropertyCreated}
      />

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

      {/* Property Detail Modal */}
      {selectedProperty && (
        <PropertyDetailModal
          lang={lang}
          property={selectedProperty}
          isOpen={showDetailModal}
          onClose={() => {
            setShowDetailModal(false);
            setSelectedProperty(null);
          }}
          onRefresh={fetchProperties}
        />
      )}
    </>
  );
}
