/**
 * Property Detail Modal Component
 * Displays full property details, image gallery, viewing history, and status controls
 */

"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
import type { Property } from "./PropertiesPanel";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  X,
  ChevronLeft,
  ChevronRight,
  Building2,
  BedDouble,
  Bath,
  Maximize2,
  Layers,
  MapPin,
  Calendar,
  Clock,
  User,
  Edit3,
  Loader2,
  Eye,
  CheckCircle2,
} from "lucide-react";

interface PropertyDetailModalProps {
  lang: Lang;
  property: Property;
  isOpen: boolean;
  onClose: () => void;
  onRefresh: () => void;
}

interface Viewing {
  id: string;
  clientName: string;
  clientPhone: string;
  viewingDate: string;
  viewingTime: string;
  brokerName?: string;
  status: string;
  feedbackRating?: number;
}

const STATUS_OPTIONS = [
  { 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: "خارج السوق" },
];

export default function PropertyDetailModal({
  lang,
  property,
  isOpen,
  onClose,
  onRefresh,
}: PropertyDetailModalProps) {
  const isAr = lang === "ar";
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [viewings, setViewings] = useState<Viewing[]>([]);
  const [loadingViewings, setLoadingViewings] = useState(false);
  const [updatingStatus, setUpdatingStatus] = useState(false);
  const [currentStatus, setCurrentStatus] = useState(property.status);

  const images = property.images || [];

  useEffect(() => {
    if (isOpen) {
      setCurrentImageIndex(0);
      setCurrentStatus(property.status);
      fetchViewings();
    }
  }, [isOpen, property.id]);

  const fetchViewings = async () => {
    try {
      setLoadingViewings(true);
      const res = await fetch(
        `/api/real-estate/properties/${property.id}/viewings`,
      );
      const data = await res.json();
      if (data.success) {
        setViewings(data.viewings || []);
      }
    } catch (error) {
      console.error("Failed to fetch viewings:", error);
    } finally {
      setLoadingViewings(false);
    }
  };

  const handleStatusChange = async (newStatus: string) => {
    setUpdatingStatus(true);
    try {
      const res = await fetchWithCSRF(
        `/api/real-estate/properties/${property.id}/status`,
        {
          method: "PATCH",
          body: JSON.stringify({ status: newStatus }),
        },
      );
      const data = await res.json();
      if (data.success) {
        setCurrentStatus(newStatus);
        onRefresh();
      }
    } catch (error) {
      console.error("Failed to update status:", error);
    } finally {
      setUpdatingStatus(false);
    }
  };

  const nextImage = () => {
    setCurrentImageIndex((prev) => (prev + 1) % images.length);
  };

  const prevImage = () => {
    setCurrentImageIndex((prev) => (prev - 1 + images.length) % images.length);
  };

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

  const getStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string }> = {
      available: { bg: "bg-emerald-100", text: "text-emerald-700" },
      reserved: { bg: "bg-amber-100", text: "text-amber-700" },
      sold: { bg: "bg-blue-100", text: "text-blue-700" },
      rented: { bg: "bg-violet-100", text: "text-violet-700" },
      off_market: { bg: "bg-slate-100", text: "text-slate-600" },
    };
    const badge = badges[status] || badges.available;
    const opt = STATUS_OPTIONS.find((o) => o.value === status);
    return (
      <span
        className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${badge.bg} ${badge.text}`}
      >
        {isAr ? opt?.labelAr : opt?.labelEn}
      </span>
    );
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div className="absolute inset-0 bg-slate-900/95 backdrop-blur-sm" />

      <div
        className="relative w-full max-w-4xl transform transition-all duration-300 ease-out animate-fadeIn max-h-[90vh] overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="absolute -inset-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500 rounded-3xl opacity-20 blur-lg" />

        <div className="relative bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
          {/* Header */}
          <div className="relative px-8 pt-6 pb-4 border-b border-slate-100 shrink-0">
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500" />
            <div className="flex items-start justify-between">
              <div>
                <div className="flex items-center gap-3">
                  <h3 className="text-xl font-bold text-slate-900">
                    {isAr ? property.titleAr : property.titleEn}
                  </h3>
                  {getStatusBadge(currentStatus)}
                </div>
                <div className="flex items-center gap-1 mt-1 text-sm text-slate-500">
                  <MapPin className="w-3.5 h-3.5" />
                  <span>
                    {property.district ? `${property.district}, ` : ""}
                    {property.city}, {property.country}
                  </span>
                </div>
              </div>
              <button
                onClick={onClose}
                className="flex h-10 w-10 items-center justify-center rounded-xl text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-all"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Body */}
          <div className="overflow-y-auto flex-1 px-8 py-6 space-y-6">
            {/* Image Gallery */}
            {images.length > 0 ? (
              <div className="relative rounded-xl overflow-hidden bg-slate-100">
                <div className="aspect-video">
                  <img
                    src={images[currentImageIndex]}
                    alt={`${isAr ? property.titleAr : property.titleEn} - ${currentImageIndex + 1}`}
                    className="w-full h-full object-cover"
                  />
                </div>
                {images.length > 1 && (
                  <>
                    <button
                      onClick={prevImage}
                      className="absolute left-3 top-1/2 -translate-y-1/2 flex h-10 w-10 items-center justify-center rounded-full bg-white/80 backdrop-blur-sm text-slate-700 hover:bg-white transition-all shadow-lg"
                    >
                      <ChevronLeft className="w-5 h-5" />
                    </button>
                    <button
                      onClick={nextImage}
                      className="absolute right-3 top-1/2 -translate-y-1/2 flex h-10 w-10 items-center justify-center rounded-full bg-white/80 backdrop-blur-sm text-slate-700 hover:bg-white transition-all shadow-lg"
                    >
                      <ChevronRight className="w-5 h-5" />
                    </button>
                    <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5">
                      {images.map((_, idx) => (
                        <button
                          key={idx}
                          onClick={() => setCurrentImageIndex(idx)}
                          className={`w-2 h-2 rounded-full transition-all ${
                            idx === currentImageIndex
                              ? "bg-white w-6"
                              : "bg-white/50"
                          }`}
                        />
                      ))}
                    </div>
                  </>
                )}
              </div>
            ) : (
              <div className="rounded-xl bg-slate-100 aspect-video flex items-center justify-center">
                <Building2 className="w-16 h-16 text-slate-300" />
              </div>
            )}

            {/* Price & Key Info */}
            <div className="flex flex-wrap items-center justify-between gap-4 p-4 rounded-xl bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200/50">
              <div>
                <p className="text-2xl font-bold text-brand-green">
                  {formatPrice(property.price, property.currency)}
                </p>
                <p className="text-xs text-slate-500 mt-0.5">
                  {property.listingType === "sale"
                    ? isAr
                      ? "للبيع"
                      : "For Sale"
                    : isAr
                      ? "للإيجار"
                      : "For Rent"}
                  {property.negotiable && (
                    <span className="ml-2 text-amber-600 font-medium">
                      ({isAr ? "قابل للتفاوض" : "Negotiable"})
                    </span>
                  )}
                </p>
              </div>
              <div className="flex items-center gap-4 text-sm text-slate-700">
                {property.bedrooms != null && (
                  <span className="flex items-center gap-1.5">
                    <BedDouble className="w-4 h-4 text-slate-400" />
                    <strong>{property.bedrooms}</strong> {isAr ? "غرف" : "Beds"}
                  </span>
                )}
                {property.bathrooms != null && (
                  <span className="flex items-center gap-1.5">
                    <Bath className="w-4 h-4 text-slate-400" />
                    <strong>{property.bathrooms}</strong>{" "}
                    {isAr ? "حمام" : "Baths"}
                  </span>
                )}
                {property.area != null && (
                  <span className="flex items-center gap-1.5">
                    <Maximize2 className="w-4 h-4 text-slate-400" />
                    <strong>{property.area}</strong> m²
                  </span>
                )}
                {property.floor != null && (
                  <span className="flex items-center gap-1.5">
                    <Layers className="w-4 h-4 text-slate-400" />
                    {isAr ? "الطابق" : "Floor"}{" "}
                    <strong>{property.floor}</strong>
                  </span>
                )}
              </div>
            </div>

            {/* Description */}
            {(property.descriptionEn || property.descriptionAr) && (
              <div>
                <h4 className="text-sm font-bold text-slate-700 mb-2">
                  {isAr ? "الوصف" : "Description"}
                </h4>
                <p className="text-sm text-slate-600 leading-relaxed whitespace-pre-wrap">
                  {isAr ? property.descriptionAr : property.descriptionEn}
                </p>
              </div>
            )}

            {/* Details Grid */}
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              <div className="rounded-lg bg-slate-50 border border-slate-200 p-3">
                <p className="text-xs text-slate-500">
                  {isAr ? "نوع العقار" : "Property Type"}
                </p>
                <p className="text-sm font-semibold text-slate-800 capitalize">
                  {property.propertyType}
                </p>
              </div>
              {property.furnishing && (
                <div className="rounded-lg bg-slate-50 border border-slate-200 p-3">
                  <p className="text-xs text-slate-500">
                    {isAr ? "التأثيث" : "Furnishing"}
                  </p>
                  <p className="text-sm font-semibold text-slate-800 capitalize">
                    {property.furnishing.replace("_", " ")}
                  </p>
                </div>
              )}
              {property.ownership && (
                <div className="rounded-lg bg-slate-50 border border-slate-200 p-3">
                  <p className="text-xs text-slate-500">
                    {isAr ? "الملكية" : "Ownership"}
                  </p>
                  <p className="text-sm font-semibold text-slate-800 capitalize">
                    {property.ownership}
                  </p>
                </div>
              )}
            </div>

            {/* Amenities */}
            {property.amenities && property.amenities.length > 0 && (
              <div>
                <h4 className="text-sm font-bold text-slate-700 mb-2">
                  {isAr ? "المرافق والخدمات" : "Amenities"}
                </h4>
                <div className="flex flex-wrap gap-2">
                  {property.amenities.map((amenity) => (
                    <span
                      key={amenity}
                      className="inline-flex items-center gap-1 rounded-lg bg-emerald-50 border border-emerald-200 px-3 py-1.5 text-xs font-medium text-emerald-700"
                    >
                      <CheckCircle2 className="w-3 h-3" />
                      {amenity.replace("_", " ")}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Status Controls */}
            <div className="rounded-xl border-2 border-slate-200 p-5">
              <h4 className="text-sm font-bold text-slate-700 mb-3">
                {isAr ? "تغيير الحالة" : "Change Status"}
              </h4>
              <div className="flex flex-wrap gap-2">
                {STATUS_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    onClick={() => handleStatusChange(opt.value)}
                    disabled={updatingStatus || currentStatus === opt.value}
                    className={`rounded-lg px-4 py-2 text-xs font-semibold transition-all ${
                      currentStatus === opt.value
                        ? "bg-brand-green text-white shadow-sm"
                        : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                    } disabled:opacity-50`}
                  >
                    {updatingStatus && currentStatus !== opt.value ? (
                      <Loader2 className="w-3 h-3 animate-spin inline mr-1" />
                    ) : null}
                    {isAr ? opt.labelAr : opt.labelEn}
                  </button>
                ))}
              </div>
            </div>

            {/* Viewing History */}
            <div>
              <h4 className="flex items-center gap-2 text-sm font-bold text-slate-700 mb-3">
                <Eye className="w-4 h-4 text-slate-500" />
                {isAr ? "سجل المعاينات" : "Viewing History"}
                <span className="text-xs text-slate-400 font-normal">
                  ({viewings.length})
                </span>
              </h4>

              {loadingViewings ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="w-5 h-5 text-brand-green animate-spin" />
                </div>
              ) : viewings.length === 0 ? (
                <div className="rounded-xl bg-slate-50 border border-slate-200 p-6 text-center">
                  <p className="text-sm text-slate-500">
                    {isAr ? "لا توجد معاينات بعد" : "No viewings scheduled yet"}
                  </p>
                </div>
              ) : (
                <div className="space-y-2">
                  {viewings.map((viewing) => (
                    <div
                      key={viewing.id}
                      className="flex items-center justify-between rounded-lg border border-slate-200 bg-slate-50/50 p-3"
                    >
                      <div className="flex items-center gap-3">
                        <div className="flex flex-col items-center justify-center w-14 rounded-lg bg-white border border-slate-200 py-1.5">
                          <p className="text-xs font-bold text-brand-green">
                            {viewing.viewingTime}
                          </p>
                          <p className="text-[10px] text-slate-400">
                            {new Date(viewing.viewingDate).toLocaleDateString(
                              isAr ? "ar-SA" : "en-US",
                              { month: "short", day: "numeric" },
                            )}
                          </p>
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-slate-900">
                            {viewing.clientName}
                          </p>
                          <p className="text-xs text-slate-500">
                            {viewing.clientPhone}
                          </p>
                          {viewing.brokerName && (
                            <p className="text-xs text-slate-400">
                              {isAr ? "الوسيط:" : "Broker:"}{" "}
                              {viewing.brokerName}
                            </p>
                          )}
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {viewing.feedbackRating && (
                          <span className="text-xs text-amber-600 font-medium">
                            {"*".repeat(viewing.feedbackRating)}
                          </span>
                        )}
                        <span
                          className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${
                            viewing.status === "completed"
                              ? "bg-emerald-100 text-emerald-700"
                              : viewing.status === "cancelled"
                                ? "bg-red-100 text-red-700"
                                : "bg-amber-100 text-amber-700"
                          }`}
                        >
                          {viewing.status}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Footer */}
          <div className="px-8 py-4 bg-gradient-to-r from-slate-50 via-slate-100/50 to-slate-50 border-t border-slate-200 shrink-0">
            <div className="flex items-center justify-between">
              <p className="text-xs text-slate-400">
                {isAr ? "أُنشئ في" : "Created"}{" "}
                {new Date(property.createdAt).toLocaleDateString(
                  isAr ? "ar-SA" : "en-US",
                )}
              </p>
              <div className="flex items-center gap-3">
                <button
                  onClick={onClose}
                  className="px-5 py-2.5 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 transition-all"
                >
                  {isAr ? "إغلاق" : "Close"}
                </button>
                <button className="px-5 py-2.5 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 hover:shadow-brand-green/50 hover:-translate-y-0.5 transition-all inline-flex items-center gap-2">
                  <Edit3 className="w-4 h-4" />
                  {isAr ? "تعديل" : "Edit"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
