'use client';

import { useState, useMemo, useEffect, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { mockShops, bangladeshDivisions } from '@/lib/mock-data';
import { getDistricts, getUpazilas, getUnions } from '@/lib/bangladesh-locations';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
/* Sheet removed - filter now uses Dialog */
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Search,
  SlidersHorizontal,
  MapPin,
  Heart,
  Maximize,
  Store,
  Phone,
  MessageCircle,
  Warehouse,
  Building,
  ShoppingBag,
  X,
  RotateCcw,
  User,
  Navigation,
} from 'lucide-react';

type ShopType = 'all' | 'commercial' | 'office' | 'warehouse' | 'retail';

interface ShopFilters {
  shopType: ShopType;
  priceMin: string;
  priceMax: string;
  division: string;
  district: string;
  upazila: string;
  union: string;
}

const shopTypeOptions: { value: ShopType; labelKey: string; icon: React.ElementType }[] = [
  { value: 'all', labelKey: 'all', icon: Store },
  { value: 'commercial', labelKey: 'shop.commercial', icon: Building },
  { value: 'office', labelKey: 'shop.office', icon: Building },
  { value: 'warehouse', labelKey: 'shop.warehouse', icon: Warehouse },
  { value: 'retail', labelKey: 'shop.retail', icon: ShoppingBag },
];

export default function ShopRentalModule() {
  const { language, setCurrentSection, setOpenChatWith } = useAppStore();
  const { toast } = useToast();

  const [searchQuery, setSearchQuery] = useState('');
  const [filterOpen, setFilterOpen] = useState(false);
  const [selectedShopId, setSelectedShopId] = useState<string | null>(null);
  const [favourites, setFavourites] = useState<Set<string>>(new Set());
  const [selectedPriceRange, setSelectedPriceRange] = useState<string | null>(null);

  // Refs for auto-scrolling in filter dialog
  const filterScrollRef = useRef<HTMLDivElement>(null);
  const districtRef = useRef<HTMLDivElement>(null);
  const upazilaRef = useRef<HTMLDivElement>(null);
  const unionRef = useRef<HTMLDivElement>(null);

  const [filters, setFilters] = useState<ShopFilters>({
    shopType: 'all',
    priceMin: '',
    priceMax: '',
    division: '',
    district: '',
    upazila: '',
    union: '',
  });

  const [appliedFilters, setAppliedFilters] = useState<ShopFilters>({
    shopType: 'all',
    priceMin: '',
    priceMax: '',
    division: '',
    district: '',
    upazila: '',
    union: '',
  });

  // Auto-scroll to newly appeared filter dropdown
  useEffect(() => {
    if (!filterOpen) return;
    const timer = setTimeout(() => {
      if (filters.union && unionRef.current) {
        unionRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      } else if (filters.upazila && upazilaRef.current) {
        upazilaRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      } else if (filters.district && districtRef.current) {
        districtRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      }
    }, 100);
    return () => clearTimeout(timer);
  }, [filters.division, filters.district, filters.upazila, filters.union, filterOpen]);

  const filteredShops = useMemo(() => {
    return mockShops.filter((shop) => {
      // Search filter
      if (searchQuery) {
        const q = searchQuery.toLowerCase();
        const matchesSearch =
          shop.title.toLowerCase().includes(q) ||
          shop.address.toLowerCase().includes(q) ||
          shop.division.toLowerCase().includes(q) ||
          shop.description.toLowerCase().includes(q);
        if (!matchesSearch) return false;
      }

      // Shop type filter
      if (appliedFilters.shopType !== 'all') {
        if (shop.shopType !== appliedFilters.shopType) return false;
      }

      // Price range filter
      if (appliedFilters.priceMin) {
        const min = parseInt(appliedFilters.priceMin);
        if (!isNaN(min) && shop.price < min) return false;
      }
      if (appliedFilters.priceMax) {
        const max = parseInt(appliedFilters.priceMax);
        if (!isNaN(max) && shop.price > max) return false;
      }

      // Division filter
      if (appliedFilters.division) {
        if (shop.division !== appliedFilters.division) return false;
      }

      // District filter
      if (appliedFilters.district) {
        if (shop.district !== appliedFilters.district) return false;
      }

      // Upazila filter
      if (appliedFilters.upazila) {
        if (shop.upazila !== appliedFilters.upazila) return false;
      }

      return true;
    });
  }, [searchQuery, appliedFilters]);

  const selectedShop = useMemo(
    () => mockShops.find((s) => s.id === selectedShopId) || null,
    [selectedShopId]
  );

  const toggleFavourite = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    setFavourites((prev) => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  const applyFilters = () => {
    setAppliedFilters({ ...filters });
    setFilterOpen(false);
  };

  const resetFilters = () => {
    const reset: ShopFilters = {
      shopType: 'all',
      priceMin: '',
      priceMax: '',
      division: '',
      district: '',
      upazila: '',
      union: '',
    };
    setFilters(reset);
    setAppliedFilters(reset);
    setSelectedPriceRange(null);
    setFilterOpen(false);
  };

  const hasActiveFilters =
    appliedFilters.shopType !== 'all' ||
    appliedFilters.priceMin !== '' ||
    appliedFilters.priceMax !== '' ||
    appliedFilters.division !== '' ||
    appliedFilters.district !== '' ||
    appliedFilters.upazila !== '' ||
    appliedFilters.union !== '';

  const getShopTypeLabel = (shopType: string) => {
    switch (shopType) {
      case 'commercial':
        return t('shop.commercial', language);
      case 'office':
        return t('shop.office', language);
      case 'warehouse':
        return t('shop.warehouse', language);
      case 'retail':
        return t('shop.retail', language);
      default:
        return shopType;
    }
  };

  const getShopTypeGradient = (shopType: string) => {
    switch (shopType) {
      case 'retail':
        return 'from-orange-400 to-amber-500';
      case 'office':
        return 'from-amber-500 to-orange-600';
      case 'warehouse':
        return 'from-orange-600 to-red-500';
      case 'commercial':
        return 'from-yellow-500 to-orange-500';
      default:
        return 'from-orange-400 to-amber-500';
    }
  };

  const getShopTypeIcon = (shopType: string) => {
    switch (shopType) {
      case 'retail':
        return ShoppingBag;
      case 'office':
        return Building;
      case 'warehouse':
        return Warehouse;
      default:
        return Store;
    }
  };

  return (
    <div className="flex min-h-[calc(100vh-8rem)] flex-col">
      {/* Header */}
      <div className="sticky top-0 z-30 border-b bg-background/95 backdrop-blur-sm">
        <div className="flex items-center gap-3 px-4 py-3">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setCurrentSection('home')}
            className="shrink-0"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <h1 className="text-lg font-bold text-foreground">
            {t('shop.title', language)}
          </h1>
          <Badge variant="secondary" className="ml-auto text-xs">
            {filteredShops.length} {language === 'bn' ? 'টি' : 'listed'}
          </Badge>
        </div>

        {/* Search & Filter Bar */}
        <div className="flex items-center gap-2 px-4 pb-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder={t('shop.search', language)}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 pr-9"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              >
                <X className="h-4 w-4" />
              </button>
            )}
          </div>
          <Button
            variant={hasActiveFilters ? 'default' : 'outline'}
            size="icon"
            onClick={() => setFilterOpen(true)}
            className="relative shrink-0"
          >
            <SlidersHorizontal className="h-4 w-4" />
            {hasActiveFilters && (
              <span className="absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] text-white">
                !
              </span>
            )}
          </Button>
        </div>

        {/* Shop Type Quick Filters */}
        <div className="flex items-center gap-2 overflow-x-auto border-t px-4 py-2 hide-scrollbar">
          {shopTypeOptions.map((option) => {
            const Icon = option.icon;
            const isActive = appliedFilters.shopType === option.value;
            return (
              <button
                key={option.value}
                onClick={() => {
                  const newType = isActive ? 'all' : option.value;
                  setFilters((f) => ({ ...f, shopType: newType }));
                  setAppliedFilters((f) => ({ ...f, shopType: newType }));
                }}
                className={`flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${
                  isActive
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
                }`}
              >
                <Icon className="h-3.5 w-3.5" />
                {option.value === 'all'
                  ? language === 'bn'
                    ? 'সব'
                    : 'All'
                  : t(option.labelKey, language)}
              </button>
            );
          })}
        </div>

        {/* Price Range Quick Filters */}
        <div className="flex items-center gap-1.5 overflow-x-auto border-t px-4 py-2 hide-scrollbar">
          <span className="shrink-0 text-[10px] text-muted-foreground">{language === 'bn' ? 'মূল্য' : 'Price'}:</span>
          {[
            { key: '0-15000', label: language === 'bn' ? '৳১৫,০০০ এর কম' : 'Under ৳15K', min: '', max: '15000' },
            { key: '15000-30000', label: '৳15K-30K', min: '15000', max: '30000' },
            { key: '30000-50000', label: '৳30K-50K', min: '30000', max: '50000' },
            { key: '50000+', label: '৳50K+', min: '50000', max: '' },
          ].map((range) => (
            <button
              key={range.key}
              onClick={() => {
                if (selectedPriceRange === range.key) {
                  setSelectedPriceRange(null);
                  setFilters((f) => ({ ...f, priceMin: '', priceMax: '' }));
                  setAppliedFilters((f) => ({ ...f, priceMin: '', priceMax: '' }));
                } else {
                  setSelectedPriceRange(range.key);
                  setFilters((f) => ({ ...f, priceMin: range.min, priceMax: range.max }));
                  setAppliedFilters((f) => ({ ...f, priceMin: range.min, priceMax: range.max }));
                }
              }}
              className={`shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${
                selectedPriceRange === range.key
                  ? 'border-primary bg-primary text-primary-foreground'
                  : 'border-border text-muted-foreground hover:border-primary/30 hover:bg-primary/5'
              }`}
            >
              {range.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content Area */}
      <div className="flex-1 px-4 py-3">
        {filteredShops.length > 0 ? (
          <div className="grid grid-cols-2 gap-3">
            {filteredShops.map((shop) => {
              const TypeIcon = getShopTypeIcon(shop.shopType);
              return (
                <Card
                  key={shop.id}
                  className="group cursor-pointer overflow-hidden border-border/50 bg-card py-0 transition-all duration-200 hover:border-primary/20 hover:shadow-md"
                  onClick={() => setSelectedShopId(shop.id)}
                >
                  {/* Image Area */}
                  <div
                    className={`relative h-28 overflow-hidden bg-gradient-to-br ${getShopTypeGradient(shop.shopType)}`}
                  >
                    {shop.images && shop.images.length > 0 ? (
                      <img src={shop.images[0]} alt={shop.title} className="h-full w-full object-cover" loading="lazy" />
                    ) : (
                      <div className="flex h-full items-center justify-center">
                        <TypeIcon className="h-8 w-8 text-white/40" />
                      </div>
                    )}
                    <Badge className="absolute left-2 top-2 bg-white/90 text-[10px] text-gray-800 backdrop-blur-sm dark:bg-black/60 dark:text-gray-100">
                      {getShopTypeLabel(shop.shopType)}
                    </Badge>
                    <Badge className={`absolute right-2 top-2 text-[9px] ${shop.isAvailable ? 'bg-emerald-500 text-white hover:bg-emerald-600' : 'bg-red-500 text-white hover:bg-red-600'}`}>
                      {shop.isAvailable ? t('house.available', language) : t('house.rented', language)}
                    </Badge>
                    <button
                      onClick={(e) => toggleFavourite(shop.id, e)}
                      className="absolute bottom-2 right-2 flex h-6 w-6 items-center justify-center rounded-full bg-white/80 backdrop-blur-sm transition-colors hover:bg-white dark:bg-black/50 dark:hover:bg-black/70"
                    >
                      <Heart
                        className={`h-3 w-3 transition-colors ${
                          favourites.has(shop.id)
                            ? 'fill-red-500 text-red-500'
                            : 'text-gray-600 dark:text-gray-300'
                        }`}
                      />
                    </button>
                  </div>

                  <CardContent className="p-2.5">
                    <h3 className="line-clamp-1 text-xs font-semibold">{shop.title}</h3>
                    <p className="text-sm font-bold text-primary">
                      ৳{shop.price.toLocaleString()}
                      <span className="text-[10px] font-normal text-muted-foreground">/{language === 'bn' ? 'মাস' : 'mo'}</span>
                    </p>
                    <p className="line-clamp-1 text-[10px] text-muted-foreground">📍 {shop.address}</p>
                    <div className="flex items-center gap-2 text-[10px] text-muted-foreground">
                      <span>📐 {shop.area} sqft</span>
                    </div>
                    <div className="mt-1 flex gap-1.5">
                      <Button size="sm" variant="outline" className="flex-1 h-7 text-[11px] gap-1" onClick={(e) => {
                        e.stopPropagation();
                        const phone = (shop as Record<string, unknown>).ownerPhone as string | undefined;
                        if (phone) {
                          window.open(`tel:${phone}`, '_self');
                        } else {
                          toast({ title: language === 'en' ? 'No phone number available' : 'ফোন নম্বর নেই', variant: 'destructive' });
                        }
                      }}>
                        <Phone className="h-3 w-3" />
                        {language === 'bn' ? 'কল' : 'Call'}
                      </Button>
                      <Button size="sm" className="flex-1 h-7 bg-gradient-to-r from-primary to-primary/90 text-[11px] gap-1" onClick={(e) => {
                        e.stopPropagation();
                        setOpenChatWith({
                          id: `owner-${shop.ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                          name: shop.ownerName,
                          listingTitle: shop.title,
                        });
                        setCurrentSection('messages');
                      }}>
                        <MessageCircle className="h-3 w-3" />
                        {language === 'bn' ? 'মেসেজ' : 'Message'}
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        ) : (
          <div className="flex flex-col items-center justify-center gap-3 py-16">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10">
              <Store className="h-8 w-8 text-primary/50" />
            </div>
            <p className="text-sm text-muted-foreground">
              {t('common.noResults', language)}
            </p>
            {hasActiveFilters && (
              <Button variant="outline" size="sm" onClick={resetFilters}>
                <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
                {language === 'bn' ? 'ফিল্টার রিসেট' : 'Reset Filters'}
              </Button>
            )}
          </div>
        )}
      </div>

      {/* Filter Dialog */}
      <Dialog open={filterOpen} onOpenChange={setFilterOpen}>
        <DialogContent className="max-w-md flex flex-col p-0 gap-0">
          <DialogHeader className="px-5 pt-5 pb-3">
            <DialogTitle>{language === 'bn' ? 'অ্যাডভান্সড ফিল্টার' : 'Advanced Filters'}</DialogTitle>
            <DialogDescription>
              {language === 'bn'
                ? 'মূল্য ও অবস্থান দিয়ে দোকান খুঁজুন'
                : 'Filter by price range and location'}
            </DialogDescription>
          </DialogHeader>

          <div ref={filterScrollRef} className="max-h-[60vh] overflow-y-auto px-5 custom-scrollbar space-y-4">
            {/* Price Range */}
            <div className="space-y-3">
              <Label className="text-sm font-semibold">
                {t('house.priceRange', language)} (৳)
              </Label>
              <div className="flex items-center gap-2">
                <Input
                  type="number"
                  placeholder={language === 'bn' ? 'সর্বনিম্ন' : 'Min'}
                  value={filters.priceMin}
                  onChange={(e) =>
                    setFilters((f) => ({ ...f, priceMin: e.target.value }))
                  }
                  className="text-xs"
                />
                <span className="text-muted-foreground">—</span>
                <Input
                  type="number"
                  placeholder={language === 'bn' ? 'সর্বোচ্চ' : 'Max'}
                  value={filters.priceMax}
                  onChange={(e) =>
                    setFilters((f) => ({ ...f, priceMax: e.target.value }))
                  }
                  className="text-xs"
                />
              </div>
            </div>

            <Separator />

            {/* Division */}
            <div className="space-y-3">
              <Label className="text-sm font-semibold">
                {language === 'bn' ? 'বিভাগ' : 'Division'}
              </Label>
              <Select
                value={filters.division}
                onValueChange={(val) =>
                  setFilters((f) => ({ ...f, division: val === 'all' ? '' : val, district: '', upazila: '', union: '' }))
                }
              >
                <SelectTrigger className="w-full">
                  <SelectValue
                    placeholder={
                      language === 'bn' ? 'বিভাগ নির্বাচন' : 'Select Division'
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">
                    {language === 'bn' ? 'সব বিভাগ' : 'All Divisions'}
                  </SelectItem>
                  {bangladeshDivisions.map((div) => (
                    <SelectItem key={div} value={div}>
                      {div}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* District - only shows when division is selected */}
            {filters.division && (
              <div ref={districtRef} className="space-y-3">
                <Label className="text-sm font-semibold">
                  {language === 'bn' ? 'জেলা' : 'District'}
                </Label>
                <Select
                  value={filters.district || 'all'}
                  onValueChange={(val) =>
                    setFilters((f) => ({ ...f, district: val === 'all' ? '' : val, upazila: '', union: '' }))
                  }
                >
                  <SelectTrigger className="w-full">
                    <SelectValue
                      placeholder={
                        language === 'bn' ? 'জেলা নির্বাচন' : 'Select District'
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">
                      {language === 'bn' ? 'সব জেলা' : 'All Districts'}
                    </SelectItem>
                    {getDistricts(filters.division).map((d) => (
                      <SelectItem key={d} value={d}>
                        {d}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* Upazila - only shows when district is selected */}
            {filters.district && (
              <div ref={upazilaRef} className="space-y-3">
                <Label className="text-sm font-semibold">
                  {language === 'bn' ? 'উপজেলা' : 'Upazila'}
                </Label>
                <Select
                  value={filters.upazila || 'all'}
                  onValueChange={(val) =>
                    setFilters((f) => ({ ...f, upazila: val === 'all' ? '' : val, union: '' }))
                  }
                >
                  <SelectTrigger className="w-full">
                    <SelectValue
                      placeholder={
                        language === 'bn' ? 'উপজেলা নির্বাচন' : 'Select Upazila'
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">
                      {language === 'bn' ? 'সব উপজেলা' : 'All Upazilas'}
                    </SelectItem>
                    {getUpazilas(filters.division, filters.district).map((u) => (
                      <SelectItem key={u} value={u}>
                        {u}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* Union - only shows when upazila is selected */}
            {filters.upazila && (
              <div ref={unionRef} className="space-y-3">
                <Label className="text-sm font-semibold">
                  {language === 'bn' ? 'ইউনিয়ন' : 'Union'}
                </Label>
                <Select
                  value={filters.union || 'all'}
                  onValueChange={(val) =>
                    setFilters((f) => ({ ...f, union: val === 'all' ? '' : val }))
                  }
                >
                  <SelectTrigger className="w-full">
                    <SelectValue
                      placeholder={
                        language === 'bn' ? 'ইউনিয়ন নির্বাচন' : 'Select Union'
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">
                      {language === 'bn' ? 'সব ইউনিয়ন' : 'All Unions'}
                    </SelectItem>
                    {getUnions(filters.division, filters.district, filters.upazila).map((u) => (
                      <SelectItem key={u} value={u}>
                        {u}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>

          {/* Filter Actions */}
          <div className="border-t bg-background px-5 py-3 flex items-center gap-3">
            <Button
              variant="outline"
              className="flex-1 h-9"
              onClick={resetFilters}
            >
              <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
              {language === 'bn' ? 'রিসেট' : 'Reset'}
            </Button>
            <Button
              className="flex-1 h-9 bg-gradient-to-r from-primary to-primary/90 font-semibold"
              onClick={applyFilters}
            >
              {language === 'bn' ? 'প্রয়োগ করুন' : 'Apply'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Shop Detail Dialog */}
      <Dialog
        open={!!selectedShopId}
        onOpenChange={(open) => {
          if (!open) setSelectedShopId(null);
        }}
      >
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          <DialogTitle className="sr-only">{selectedShop?.title || 'Shop Details'}</DialogTitle>
          <DialogDescription className="sr-only">{selectedShop?.address || 'Shop rental details'}</DialogDescription>
          {selectedShop && (
            <div className="space-y-4">
              {/* Back Button */}
              <Button variant="ghost" size="sm" onClick={() => setSelectedShopId(null)} className="gap-1.5 text-orange-600 hover:text-orange-700 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-950/30">
                <ArrowLeft className="h-4 w-4" />
                <span>{language === 'en' ? 'Back to Shops' : 'দোকানে ফিরুন'}</span>
              </Button>
              {/* Image Area */}
              <div
                className={`relative h-52 overflow-hidden rounded-lg bg-gradient-to-br ${getShopTypeGradient(selectedShop.shopType)}`}
              >
                {selectedShop.images && selectedShop.images.length > 0 ? (
                  <img src={selectedShop.images[0]} alt={selectedShop.title} className="h-full w-full object-cover" loading="lazy" />
                ) : (
                  <div className="flex h-full items-center justify-center">
                    {(() => {
                      const Icon = getShopTypeIcon(selectedShop.shopType);
                      return <Icon className="h-20 w-20 text-white/30" />;
                    })()}
                  </div>
                )}
                <div className="absolute left-3 top-3 flex flex-wrap gap-1.5">
                  <Badge className="bg-emerald-500 text-white hover:bg-emerald-600 text-xs">
                    {selectedShop.isAvailable
                      ? t('house.available', language)
                      : t('house.rented', language)}
                  </Badge>
                  <Badge
                    variant="secondary"
                    className="bg-white/90 text-xs text-gray-800 backdrop-blur-sm dark:bg-black/60 dark:text-gray-100"
                  >
                    {getShopTypeLabel(selectedShop.shopType)}
                  </Badge>
                </div>
              </div>

              {/* Title & Price */}
              <DialogHeader>
                <DialogTitle className="text-lg leading-tight">
                  {selectedShop.title}
                </DialogTitle>
                <DialogDescription className="sr-only">
                  {selectedShop.description}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-3">
                <p className="text-2xl font-bold text-primary">
                  ৳{selectedShop.price.toLocaleString()}
                  <span className="text-sm font-normal text-muted-foreground">
                    {t('house.perMonth', language)}
                  </span>
                </p>

                {/* Quick Info Grid */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3">
                    <Maximize className="h-5 w-5 text-primary" />
                    <span className="text-xs font-semibold">{selectedShop.area} sqft</span>
                    <span className="text-[10px] text-muted-foreground">
                      {t('house.area', language)}
                    </span>
                  </div>
                  <div className="flex flex-col items-center gap-1 rounded-lg bg-primary/5 p-3">
                    {(() => {
                      const TypeIcon = getShopTypeIcon(selectedShop.shopType);
                      return <TypeIcon className="h-5 w-5 text-primary" />;
                    })()}
                    <span className="text-xs font-semibold">
                      {getShopTypeLabel(selectedShop.shopType)}
                    </span>
                    <span className="text-[10px] text-muted-foreground">
                      {language === 'bn' ? 'ধরন' : 'Type'}
                    </span>
                  </div>
                </div>

                <Separator />

                {/* Description */}
                <div>
                  <h4 className="mb-1.5 text-sm font-semibold text-foreground">
                    {language === 'bn' ? 'বিবরণ' : 'Description'}
                  </h4>
                  <p className="text-xs leading-relaxed text-muted-foreground">
                    {selectedShop.description}
                  </p>
                </div>

                <Separator />

                {/* Location */}
                <div>
                  <h4 className="mb-1.5 text-sm font-semibold text-foreground">
                    {language === 'bn' ? 'অবস্থান' : 'Location'}
                  </h4>
                  <div className="flex items-start gap-2 text-xs text-muted-foreground">
                    <MapPin className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
                    <div>
                      <p>{selectedShop.address}</p>
                      <p>
                        {selectedShop.upazila}, {selectedShop.district},{' '}
                        {selectedShop.division}
                      </p>
                    </div>
                  </div>
                  {/* Google Map */}
                  <div className="mt-3 overflow-hidden rounded-lg border shadow-sm">
                    <iframe
                      src={`https://maps.google.com/maps?q=${encodeURIComponent(`${selectedShop.address}, ${selectedShop.upazila}, ${selectedShop.district}, ${selectedShop.division}, Bangladesh`)}&output=embed`}
                      width="100%"
                      height="200"
                      style={{ border: 0 }}
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      className="w-full"
                      title="Location Map"
                    />
                  </div>
                  {/* Open in Google Maps button */}
                  <Button
                    variant="outline"
                    className="w-full gap-1.5 text-xs mt-2"
                    onClick={() => {
                      const query = encodeURIComponent(`${selectedShop.address}, ${selectedShop.upazila}, ${selectedShop.district}, ${selectedShop.division}, Bangladesh`);
                      window.open(`https://www.google.com/maps/search/?api=1&query=${query}`, '_blank');
                    }}
                  >
                    <MapPin className="h-3.5 w-3.5" />
                    {language === 'en' ? 'Open in Google Maps' : 'গুগল ম্যাপে খুলুন'}
                  </Button>
                  {/* Get Directions button */}
                  <Button
                    variant="outline"
                    className="w-full gap-1.5 text-xs mt-1.5"
                    onClick={() => {
                      const query = encodeURIComponent(`${selectedShop.address}, ${selectedShop.upazila}, ${selectedShop.district}, ${selectedShop.division}, Bangladesh`);
                      window.open(`https://www.google.com/maps/dir/?api=1&destination=${query}`, '_blank');
                    }}
                  >
                    <Navigation className="h-3.5 w-3.5" />
                    {language === 'en' ? 'Get Directions' : 'দিকনির্দেশনা পান'}
                  </Button>
                </div>

                <Separator />

                {/* Owner Info */}
                <div>
                  <h4 className="mb-2 text-sm font-semibold text-foreground">
                    {language === 'bn' ? 'মালিকের তথ্য' : 'Owner Info'}
                  </h4>
                  <div className="flex items-center gap-3 rounded-lg bg-muted/50 p-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
                      <User className="h-5 w-5 text-primary" />
                    </div>
                    <div className="flex-1">
                      <p className="text-sm font-medium">{selectedShop.ownerName}</p>
                      <p className="text-xs text-muted-foreground">
                        {language === 'bn' ? 'সম্পত্তির মালিক' : 'Property Owner'}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex flex-col gap-2 pt-2 sm:flex-row">
                <Button
                  variant="outline"
                  className="flex-1 gap-1.5"
                  onClick={() => {
                    const phone = (selectedShop as Record<string, unknown>).ownerPhone as string | undefined;
                    if (phone) {
                      window.open(`tel:${phone}`, '_self');
                    } else {
                      toast({ title: language === 'en' ? 'No phone number available' : 'ফোন নম্বর নেই', variant: 'destructive' });
                    }
                  }}
                >
                  <Phone className="h-4 w-4" />
                  {language === 'bn' ? 'কল' : 'Call'}
                </Button>
                <Button
                  className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold gap-1.5"
                  onClick={() => {
                    setSelectedShopId(null);
                    setOpenChatWith({
                      id: `owner-${selectedShop.ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                      name: selectedShop.ownerName,
                      listingTitle: selectedShop.title,
                    });
                    setCurrentSection('messages');
                  }}
                >
                  <MessageCircle className="h-4 w-4" />
                  {language === 'bn' ? 'মেসেজ' : 'Message'}
                </Button>
                <Button
                  variant="outline"
                  className="flex-1"
                  onClick={() => toggleFavourite(selectedShop.id)}
                >
                  <Heart
                    className={`mr-1.5 h-4 w-4 ${
                      favourites.has(selectedShop.id)
                        ? 'fill-red-500 text-red-500'
                        : ''
                    }`}
                  />
                  {t('house.favourite', language)}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
