'use client';

import { useState, useMemo, useCallback, 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 { Textarea } from '@/components/ui/textarea';
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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import {
  ArrowLeft,
  Search,
  SlidersHorizontal,
  MapPin,
  Heart,
  Maximize,
  Store,
  Phone,
  MessageCircle,
  Warehouse,
  Building,
  ShoppingBag,
  X,
  RotateCcw,
  User,
  Navigation,
  Star,
  Plus,
  Edit3,
  Trash2,
  Eye,
  EyeOff,
  ImagePlus,
} 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 },
];

interface DbShop {
  id: string;
  title: string;
  description: string;
  price: number;
  shopType: string;
  area: number | null;
  isAvailable: boolean;
  images: string;
  address: string;
  division: string;
  district: string;
  upazila: string | null;
  createdAt: string;
  owner: { id: string; name: string; phone: string | null; avatar: string | null };
}

// ─── Shop Upload Form ──────────────────────────────────────────
function ShopUploadForm({
  language,
  ownerId,
  onShopPosted,
  editShop,
  onCancelEdit,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onShopPosted: () => void;
  editShop: DbShop | null;
  onCancelEdit: () => void;
}) {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [urlInput, setUrlInput] = useState('');

  const parseImages = (images: string | string[] | null | undefined): string[] => {
    if (!images) return [];
    if (Array.isArray(images)) return images;
    try {
      const parsed = JSON.parse(images);
      return Array.isArray(parsed) ? parsed : [];
    } catch { return []; }
  };

  const [form, setForm] = useState({
    title: editShop?.title || '',
    description: editShop?.description || '',
    price: editShop?.price?.toString() || '',
    shopType: editShop?.shopType || 'commercial',
    area: editShop?.area?.toString() || '',
    address: editShop?.address || '',
    division: editShop?.division || '',
    district: editShop?.district || '',
    upazila: editShop?.upazila || '',
    imageUrls: parseImages(editShop?.images),
  });

  useEffect(() => {
    if (editShop) {
      setForm({
        title: editShop.title,
        description: editShop.description,
        price: editShop.price.toString(),
        shopType: editShop.shopType,
        area: editShop.area?.toString() || '',
        address: editShop.address,
        division: editShop.division,
        district: editShop.district,
        upazila: editShop.upazila || '',
        imageUrls: parseImages(editShop.images),
      });
    }
  }, [editShop]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title || !form.description || !form.price || !form.address || !form.division || !form.district) {
      toast({ title: 'Please fill all required fields', variant: 'destructive' });
      return;
    }

    setIsLoading(true);
    try {
      if (editShop) {
        const res = await fetch('/api/shops', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: editShop.id,
            title: form.title,
            description: form.description,
            price: parseFloat(form.price),
            shopType: form.shopType,
            area: form.area ? parseFloat(form.area) : null,
            address: form.address,
            division: form.division,
            district: form.district,
            upazila: form.upazila || null,
            images: form.imageUrls,
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: language === 'en' ? 'Shop updated!' : 'দোকান আপডেট হয়েছে!' });
          onShopPosted();
          onCancelEdit();
        } else {
          toast({ title: data.error || 'Failed to update', variant: 'destructive' });
        }
      } else {
        const res = await fetch('/api/shops', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            title: form.title,
            description: form.description,
            price: parseFloat(form.price),
            shopType: form.shopType,
            area: form.area ? parseFloat(form.area) : null,
            address: form.address,
            division: form.division,
            district: form.district,
            upazila: form.upazila || null,
            images: form.imageUrls,
            ownerId,
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: language === 'en' ? 'Shop posted!' : 'দোকান পোস্ট হয়েছে!' });
          onShopPosted();
          setForm({
            title: '', description: '', price: '', shopType: 'commercial',
            area: '', address: '', division: '', district: '', upazila: '', imageUrls: [],
          });
          setUrlInput('');
        } else {
          toast({ title: data.error || 'Failed to post', variant: 'destructive' });
        }
      }
    } catch {
      toast({ title: 'Network error', variant: 'destructive' });
    } finally {
      setIsLoading(false);
    }
  };

  const inputClass = 'text-sm h-9';

  return (
    <form onSubmit={handleSubmit} className="space-y-3">
      {editShop && (
        <div className="rounded-lg border border-primary/20 bg-primary/5 p-2.5 text-center text-xs font-medium text-primary">
          {language === 'en' ? 'Editing' : 'সম্পাদনা করছেন'}: {editShop.title}
        </div>
      )}

      {/* Title */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{language === 'en' ? 'Shop Title' : 'দোকানের নাম'} *</Label>
        <Input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder={language === 'en' ? 'e.g. Commercial Space in Gulshan' : 'যেমন: গুলশানে বাণিজ্যিক স্থান'} className={inputClass} required />
      </div>

      {/* Description */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.description', language)} *</Label>
        <Textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder={language === 'en' ? 'Describe your shop...' : 'আপনার দোকানের বিবরণ...'} className="min-h-[60px] text-sm" required />
      </div>

      {/* Shop Type & Price */}
      <div className="grid grid-cols-2 gap-2">
        <div className="space-y-1">
          <Label className="text-xs font-medium">{language === 'en' ? 'Shop Type' : 'দোকানের ধরন'} *</Label>
          <select value={form.shopType} onChange={(e) => setForm({ ...form, shopType: e.target.value })} className="w-full rounded-md border bg-background px-2 py-2 text-sm h-9">
            <option value="commercial">{t('shop.commercial', language)}</option>
            <option value="office">{t('shop.office', language)}</option>
            <option value="warehouse">{t('shop.warehouse', language)}</option>
            <option value="retail">{t('shop.retail', language)}</option>
          </select>
        </div>
        <div className="space-y-1">
          <Label className="text-xs font-medium">{t('house.monthlyRent', language)} *</Label>
          <Input type="number" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="25000" className={inputClass} required />
        </div>
      </div>

      {/* Area */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.areaSqft', language)}</Label>
        <Input type="number" value={form.area} onChange={(e) => setForm({ ...form, area: e.target.value })} placeholder="800" className={inputClass} min="0" />
      </div>

      {/* Image Upload */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{language === 'en' ? 'Shop Images' : 'দোকানের ছবি'}</Label>
        <div className="flex gap-2">
          <Input
            value={urlInput}
            onChange={(e) => setUrlInput(e.target.value)}
            placeholder={language === 'en' ? 'Paste image URL and click Add' : 'ছবির লিঙ্ক পেস্ট করুন'}
            className={`${inputClass} flex-1`}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && urlInput.trim()) {
                e.preventDefault();
                setForm((prev) => ({ ...prev, imageUrls: [...prev.imageUrls, urlInput.trim()] }));
                setUrlInput('');
              }
            }}
          />
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="h-9 px-3 shrink-0"
            disabled={!urlInput.trim()}
            onClick={() => {
              if (urlInput.trim()) {
                setForm((prev) => ({ ...prev, imageUrls: [...prev.imageUrls, urlInput.trim()] }));
                setUrlInput('');
              }
            }}
          >
            {language === 'en' ? 'Add' : 'যোগ'}
          </Button>
        </div>
        <input
          type="file"
          ref={fileInputRef}
          accept="image/*"
          multiple
          className="hidden"
          onChange={async (e) => {
            const files = e.target.files;
            if (!files || files.length === 0) return;
            setUploading(true);
            try {
              const newUrls: string[] = [];
              for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const formData = new FormData();
                formData.append('file', file);
                formData.append('category', 'shop');
                const res = await fetch('/api/upload', { method: 'POST', body: formData });
                if (res.ok) {
                  const data = await res.json();
                  newUrls.push(data.url);
                }
              }
              if (newUrls.length > 0) {
                setForm((prev) => ({ ...prev, imageUrls: [...prev.imageUrls, ...newUrls] }));
              }
            } catch (err) {
              console.error('Upload error:', err);
              toast({ title: 'Upload failed', variant: 'destructive' });
            } finally {
              setUploading(false);
              if (fileInputRef.current) fileInputRef.current.value = '';
            }
          }}
        />
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="h-9 w-full gap-1.5"
          disabled={uploading}
          onClick={() => fileInputRef.current?.click()}
        >
          {uploading ? (
            <span className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          ) : (
            <ImagePlus className="h-4 w-4" />
          )}
          {uploading
            ? (language === 'en' ? 'Uploading...' : 'আপলোড হচ্ছে...')
            : (language === 'en' ? 'Upload Image(s)' : 'ছবি আপলোড করুন')}
        </Button>
        {form.imageUrls.length > 0 && (
          <div className="flex flex-wrap gap-2 mt-1">
            {form.imageUrls.map((url, idx) => (
              <div key={idx} className="relative h-16 w-16 overflow-hidden rounded-md border bg-muted/30">
                <img src={url} alt={`Image ${idx + 1}`} className="h-full w-full object-cover" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                <button
                  type="button"
                  className="absolute top-0.5 right-0.5 h-4 w-4 rounded-full bg-black/60 text-white flex items-center justify-center text-[10px] leading-none hover:bg-black/80"
                  onClick={() => setForm((prev) => ({ ...prev, imageUrls: prev.imageUrls.filter((_, i) => i !== idx) }))}
                >×</button>
              </div>
            ))}
          </div>
        )}
        {form.imageUrls.length === 0 && !urlInput && (
          <p className="text-[11px] text-muted-foreground">{language === 'en' ? 'Add images via URL or upload from device' : 'URL বা ডিভাইস থেকে ছবি যোগ করুন'}</p>
        )}
      </div>

      <Separator className="my-1" />

      {/* Address */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.addressLine', language)} *</Label>
        <Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} placeholder={language === 'en' ? 'Shop 5, Market Road' : 'দোকান ৫, মার্কেট রোড'} className={inputClass} required />
      </div>

      {/* Division */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.division', language)} *</Label>
        <select
          value={form.division}
          onChange={(e) => setForm({ ...form, division: e.target.value, district: '', upazila: '' })}
          className="w-full rounded-md border bg-background px-2 py-2 text-sm h-9"
          required
        >
          <option value="">{language === 'en' ? 'Select Division' : 'বিভাগ নির্বাচন'}</option>
          {bangladeshDivisions.map((d) => <option key={d} value={d}>{d}</option>)}
        </select>
      </div>

      {/* District */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.district', language)} *</Label>
        {form.division && getDistricts(form.division).length > 0 ? (
          <select
            value={form.district}
            onChange={(e) => setForm({ ...form, district: e.target.value, upazila: '' })}
            className="w-full rounded-md border bg-background px-2 py-2 text-sm h-9"
            required
          >
            <option value="">{language === 'en' ? 'Select District' : 'জেলা নির্বাচন'}</option>
            {getDistricts(form.division).map((d) => <option key={d} value={d}>{d}</option>)}
          </select>
        ) : (
          <Input
            value={form.district}
            onChange={(e) => setForm({ ...form, district: e.target.value })}
            placeholder={form.division ? (language === 'en' ? 'Select division first' : 'প্রথমে বিভাগ নির্বাচন করুন') : (language === 'en' ? 'Dhaka' : 'ঢাকা')}
            className={inputClass}
            required
            disabled={!form.division}
          />
        )}
      </div>

      {/* Upazila */}
      <div className="space-y-1">
        <Label className="text-xs font-medium">{t('house.upazila', language)}</Label>
        {form.district && getUpazilas(form.division, form.district).length > 0 ? (
          <select
            value={form.upazila}
            onChange={(e) => setForm({ ...form, upazila: e.target.value })}
            className="w-full rounded-md border bg-background px-2 py-2 text-sm h-9"
          >
            <option value="">{language === 'en' ? 'Select Upazila' : 'উপজেলা নির্বাচন'}</option>
            {getUpazilas(form.division, form.district).map((u) => <option key={u} value={u}>{u}</option>)}
          </select>
        ) : (
          <Input
            value={form.upazila}
            onChange={(e) => setForm({ ...form, upazila: e.target.value })}
            placeholder={form.district ? (language === 'en' ? 'Select district first' : 'প্রথমে জেলা নির্বাচন করুন') : (language === 'en' ? 'Gulshan' : 'গুলশান')}
            className={inputClass}
            disabled={!form.district}
          />
        )}
      </div>

      {/* Action Buttons */}
      <div className="flex gap-2 pt-2">
        {editShop && (
          <Button type="button" variant="outline" className="flex-1 h-9" onClick={onCancelEdit}>
            {t('common.cancel', language)}
          </Button>
        )}
        <Button type="submit" className="flex-1 h-9 bg-gradient-to-r from-primary to-primary/90 font-semibold" disabled={isLoading}>
          {isLoading ? t('common.loading', language) : editShop ? t('common.save', language) : (language === 'en' ? 'Post Shop' : 'দোকান পোস্ট করুন')}
        </Button>
      </div>
    </form>
  );
}

// ─── Owner's Shops Section ─────────────────────────────────────
function OwnerShops({
  language,
  ownerId,
  onRefresh,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onRefresh: () => void;
}) {
  const { toast } = useToast();
  const [shops, setShops] = useState<DbShop[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingShop, setEditingShop] = useState<DbShop | null>(null);
  const [uploadOpen, setUploadOpen] = useState(false);

  const fetchMyShops = useCallback(async () => {
    try {
      const res = await fetch(`/api/shops/my?ownerId=${ownerId}`);
      const data = await res.json();
      if (data.shops) setShops(data.shops);
    } catch (err) {
      console.error('Failed to fetch my shops:', err);
    } finally {
      setLoading(false);
    }
  }, [ownerId]);

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

  const handleToggleAvailable = async (shopId: string, current: boolean) => {
    try {
      const res = await fetch('/api/shops', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: shopId, isAvailable: !current }),
      });
      if (res.ok) {
        toast({ title: current ? (language === 'en' ? 'Marked as rented' : 'ভাড়া হয়েছে') : (language === 'en' ? 'Now available' : 'এখন পাওয়া যাচ্ছে') });
        fetchMyShops();
      }
    } catch (err) {
      console.error('Failed to toggle:', err);
    }
  };

  const handleDelete = async (shopId: string) => {
    try {
      const res = await fetch('/api/shops', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: shopId }),
      });
      if (res.ok) {
        toast({ title: language === 'en' ? 'Shop deleted' : 'দোকান মুছে ফেলা হয়েছে' });
        fetchMyShops();
      }
    } catch (err) {
      console.error('Failed to delete:', err);
    }
  };

  const handleEdit = (shop: DbShop) => {
    setEditingShop(shop);
    setUploadOpen(true);
  };

  const handleNewShop = () => {
    setEditingShop(null);
    setUploadOpen(true);
  };

  const handleShopPosted = () => {
    fetchMyShops();
    onRefresh();
    setUploadOpen(false);
  };

  const getShopImages = (shop: { images?: string | string[] }): string[] => {
    if (!shop.images) return [];
    if (Array.isArray(shop.images)) return shop.images;
    try {
      const parsed = JSON.parse(shop.images);
      return Array.isArray(parsed) ? parsed : [];
    } catch { return []; }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-base font-bold">{language === 'en' ? 'My Shops' : 'আমার দোকান'}</h2>
        <Button size="sm" className="gap-1" onClick={handleNewShop}>
          <Plus className="h-4 w-4" />
          {language === 'en' ? 'Post Shop' : 'দোকান পোস্ট'}
        </Button>
      </div>

      <Dialog open={uploadOpen} onOpenChange={setUploadOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg custom-scrollbar w-[95vw] max-w-[95vw] sm:w-auto sm:max-w-lg p-4 sm:p-6">
          <DialogHeader>
            <DialogTitle className="text-base">{editingShop ? (language === 'en' ? 'Edit Shop' : 'দোকান সম্পাদনা') : (language === 'en' ? 'Upload Shop' : 'দোকান আপলোড')}</DialogTitle>
            <DialogDescription className="text-xs">
              {language === 'en'
                ? 'Fill in the details to list your shop'
                : 'আপনার দোকান তালিকাভুক্ত করতে বিস্তারিত পূরণ করুন'}
            </DialogDescription>
          </DialogHeader>
          <ShopUploadForm
            language={language}
            ownerId={ownerId}
            onShopPosted={handleShopPosted}
            editShop={editingShop}
            onCancelEdit={() => { setEditingShop(null); setUploadOpen(false); }}
          />
        </DialogContent>
      </Dialog>

      {shops.length === 0 ? (
        <Card className="py-8">
          <CardContent className="flex flex-col items-center gap-3 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10">
              <Store className="h-8 w-8 text-primary/40" />
            </div>
            <p className="text-sm text-muted-foreground">
              {language === 'en' ? 'No shops listed yet' : 'এখনো কোনো দোকান তালিকাভুক্ত নেই'}
            </p>
            <Button size="sm" variant="outline" onClick={handleNewShop} className="gap-1">
              <Plus className="h-4 w-4" />
              {language === 'en' ? 'Post Shop' : 'দোকান পোস্ট'}
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3 sm:grid-cols-2">
          {shops.map((shop) => {
            const TypeIcon = (() => {
              switch (shop.shopType) {
                case 'retail': return ShoppingBag;
                case 'office': return Building;
                case 'warehouse': return Warehouse;
                default: return Store;
              }
            })();
            return (
              <Card key={shop.id} className="overflow-hidden transition-shadow hover:shadow-md">
                <div className={`relative h-28 overflow-hidden bg-gradient-to-br ${
                  shop.shopType === 'retail' ? 'from-orange-400 to-amber-500' :
                  shop.shopType === 'office' ? 'from-amber-500 to-orange-600' :
                  shop.shopType === 'warehouse' ? 'from-orange-600 to-red-500' :
                  'from-yellow-500 to-orange-500'
                }`}>
                  {getShopImages(shop).length > 0 ? (
                    <img src={getShopImages(shop)[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-12 w-12 text-white/30" />
                    </div>
                  )}
                  <Badge className={`absolute left-3 top-3 text-[10px] ${
                    shop.isAvailable
                      ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                      : 'bg-red-500 text-white hover:bg-red-600'
                  }`}>
                    {shop.isAvailable ? (language === 'en' ? 'Available' : 'পাওয়া যাচ্ছে') : (language === 'en' ? 'Rented' : 'ভাড়া হয়েছে')}
                  </Badge>
                </div>
                <CardContent className="p-3">
                  <h3 className="truncate text-sm font-semibold">{shop.title}</h3>
                  <div className="mt-1 flex items-center gap-2">
                    <span className="text-base font-bold text-primary">৳{shop.price.toLocaleString()}</span>
                    <span className="text-[10px] text-muted-foreground">{t('house.perMonth', language)}</span>
                  </div>
                  <div className="mt-3 flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1 text-[11px]"
                      onClick={() => handleToggleAvailable(shop.id, shop.isAvailable)}
                    >
                      {shop.isAvailable ? (
                        <><EyeOff className="mr-1 h-3 w-3" />{language === 'en' ? 'Mark Rented' : 'ভাড়া চিহ্নিত'}</>
                      ) : (
                        <><Eye className="mr-1 h-3 w-3" />{language === 'en' ? 'Available' : 'পাওয়া যাচ্ছে'}</>
                      )}
                    </Button>
                    <Button variant="outline" size="sm" className="text-[11px]" onClick={() => handleEdit(shop)}>
                      <Edit3 className="h-3 w-3" />
                    </Button>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="outline" size="sm" className="text-[11px] text-destructive hover:bg-destructive/5">
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>{t('admin.deleteConfirm', language)}</AlertDialogTitle>
                          <AlertDialogDescription>
                            {language === 'en'
                              ? `This will permanently delete "${shop.title}".`
                              : `এটি "${shop.title}" স্থায়ীভাবে মুছে ফেলবে।`}
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>{t('common.cancel', language)}</AlertDialogCancel>
                          <AlertDialogAction className="bg-destructive text-destructive-foreground" onClick={() => handleDelete(shop.id)}>
                            {t('common.delete', language)}
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default function ShopRentalModule() {
  const { language, setCurrentSection, setOpenChatWith, isLoggedIn, user } = 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);
  const [ownerMode, setOwnerMode] = useState(false);

  // API shops state - fetch from database
  const [apiShops, setApiShops] = useState<any[]>([]);
  const [refreshKey, setRefreshKey] = useState(0);

  const isShopOwner = isLoggedIn && user?.roles?.includes('shopOwner');

  // Review state for detail dialog
  const [shopReviews, setShopReviews] = useState<{ reviews: { id: string; userId: string; rating: number; comment: string | null; createdAt: string; userName: string; userAvatar: string | null }[]; averageRating: number; totalReviews: number }>({ reviews: [], averageRating: 0, totalReviews: 0 });
  const [userRating, setUserRating] = useState(0);
  const [reviewComment, setReviewComment] = useState('');
  const [submittingReview, setSubmittingReview] = useState(false);

  // 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: '',
  });

  // Fetch shops from API on mount and when refreshKey changes
  useEffect(() => {
    const fetchShops = async () => {
      try {
        const res = await fetch('/api/shops?limit=100');
        const data = await res.json();
        if (data.shops) setApiShops(data.shops);
      } catch (err) {
        console.error('Failed to fetch shops:', err);
      }
    };
    fetchShops();
  }, [refreshKey]);

  // Fetch reviews when shop detail dialog opens
  useEffect(() => {
    if (selectedShopId) {
      fetch(`/api/reviews?reviewType=shop&referenceId=${selectedShopId}`)
        .then(res => res.json())
        .then(data => {
          if (data.reviews) setShopReviews(data);
        })
        .catch(() => {});
    }
  }, [selectedShopId]);

  // 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(() => {
    // Combine mock shops with API shops, API shops take precedence
    const allShops = [...apiShops, ...mockShops.filter(ms => !apiShops.some(as2 => as2.id === ms.id))];

    return allShops.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, apiShops]);

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

  // Helper: safely get owner info from either API shop (owner.name) or mock shop (ownerName)
  const getOwnerName = (shop: { ownerName?: string; owner?: { name?: string } } | null) => shop?.ownerName || (shop as any)?.owner?.name || '';
  const getOwnerPhone = (shop: { ownerPhone?: string; owner?: { phone?: string | null } } | null) => shop?.ownerPhone || (shop as any)?.owner?.phone || '';
  const getOwnerId = (shop: { ownerId?: string; owner?: { id?: string } } | null) => shop?.ownerId || (shop as any)?.owner?.id || '';

  // Helper: parse images field (API returns JSON string, mock data returns array)
  const getShopImages = (shop: { images?: string | string[] }): string[] => {
    if (!shop.images) return [];
    if (Array.isArray(shop.images)) return shop.images;
    try {
      const parsed = JSON.parse(shop.images);
      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  };

  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>
          {isShopOwner && (
            <Button
              size="sm"
              variant={ownerMode ? 'default' : 'outline'}
              className="ml-auto gap-1 text-xs"
              onClick={() => setOwnerMode(!ownerMode)}
            >
              <Store className="h-3.5 w-3.5" />
              {ownerMode ? (language === 'en' ? 'Browse' : 'ব্রাউজ') : (language === 'en' ? 'My Shops' : 'আমার দোকান')}
            </Button>
          )}
          {!ownerMode && (
            <Badge variant="secondary" className={`${isShopOwner ? '' : 'ml-auto'} text-xs`}>
              {filteredShops.length} {language === 'bn' ? 'টি' : 'listed'}
            </Badge>
          )}
        </div>

        {/* Search & Filter Bar - only in browse mode */}
        {!ownerMode && (
        <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 - only in browse mode */}
        {!ownerMode && (
        <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 - only in browse mode */}
        {!ownerMode && (
        <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">
        {ownerMode && isShopOwner && user ? (
          <OwnerShops language={language} ownerId={user.id} onRefresh={() => setRefreshKey((k) => k + 1)} />
        ) : 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)}`}
                  >
                    {getShopImages(shop).length > 0 ? (
                      <img src={getShopImages(shop)[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>
                    {/* Rating overlay - only show if shop has rating */}
                    {(shop as Record<string, unknown>).rating && Number((shop as Record<string, unknown>).rating) > 0 && (
                      <div className="absolute bottom-2 left-2 flex items-center gap-0.5 rounded-full bg-black/60 px-1.5 py-0.5 backdrop-blur-sm">
                        <Star className="h-2.5 w-2.5 fill-amber-400 text-amber-400" />
                        <span className="text-[9px] font-medium text-white">{Number((shop as Record<string, unknown>).rating)}</span>
                      </div>
                    )}

                  </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 = getOwnerPhone(shop);
                        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" variant="outline" className="h-7 w-7 shrink-0 p-0" onClick={(e) => {
                        e.stopPropagation();
                        const ownerName = getOwnerName(shop);
                        setOpenChatWith({
                          id: getOwnerId(shop) || `owner-${ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                          name: ownerName,
                          listingTitle: shop.title,
                        });
                        setCurrentSection('messages');
                      }}>
                        <MessageCircle className="h-3.5 w-3.5" />
                      </Button>
                      <Button size="sm" variant="outline" className="h-7 w-7 shrink-0 p-0" onClick={(e) => { e.stopPropagation(); toggleFavourite(shop.id); }}>
                        <Heart className={`h-3.5 w-3.5 transition-colors ${favourites.has(shop.id) ? 'fill-red-500 text-red-500' : 'text-muted-foreground'}`} />
                      </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); setUserRating(0); setReviewComment(''); }
        }}
      >
        <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">
              {/* Image Area */}
              <div
                className={`relative h-52 overflow-hidden rounded-lg bg-gradient-to-br ${getShopTypeGradient(selectedShop.shopType)}`}
              >
                {getShopImages(selectedShop).length > 0 ? (
                  <img src={getShopImages(selectedShop)[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>
                {/* Rating on detail image */}
                {(selectedShop as Record<string, unknown>).rating && Number((selectedShop as Record<string, unknown>).rating) > 0 && (
                  <div className="absolute bottom-3 left-3 flex items-center gap-1 rounded-full bg-black/60 px-2 py-1 backdrop-blur-sm">
                    <Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" />
                    <span className="text-xs font-bold text-white">{Number((selectedShop as Record<string, unknown>).rating)}</span>
                    {(selectedShop as Record<string, unknown>).reviewCount && <span className="text-[10px] text-white/70">({Number((selectedShop as Record<string, unknown>).reviewCount)})</span>}
                  </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">{getOwnerName(selectedShop) || (language === 'bn' ? 'মালিক' : 'Owner')}</p>
                      <p className="text-xs text-muted-foreground">
                        {language === 'bn' ? 'সম্পত্তির মালিক' : 'Property Owner'}
                      </p>
                    </div>
                  </div>
                </div>
                <Separator />
                {/* Reviews & Rating Section */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="text-sm font-semibold text-foreground">{language === 'bn' ? 'রিভিউ ও রেটিং' : 'Reviews & Rating'}</h4>
                    {shopReviews.totalReviews > 0 && (
                      <div className="flex items-center gap-1">
                        <Star className="h-4 w-4 fill-amber-400 text-amber-400" />
                        <span className="text-sm font-bold">{shopReviews.averageRating}</span>
                        <span className="text-xs text-muted-foreground">({shopReviews.totalReviews})</span>
                      </div>
                    )}
                  </div>
                  {isLoggedIn && (
                    <div className="mb-3 rounded-lg bg-muted/50 p-3">
                      <p className="text-xs font-medium mb-2">{language === 'bn' ? 'আপনার রেটিং দিন' : 'Rate this listing'}</p>
                      <div className="flex gap-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <button key={star} onClick={() => setUserRating(star)} className="transition-transform hover:scale-110">
                            <Star className={`h-6 w-6 ${star <= userRating ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground/30'}`} />
                          </button>
                        ))}
                      </div>
                      {userRating > 0 && (
                        <div className="mt-2 space-y-2">
                          <Textarea placeholder={language === 'bn' ? 'আপনার মতামত লিখুন (ঐচ্ছিক)' : 'Write your review (optional)'} value={reviewComment} onChange={(e) => setReviewComment(e.target.value)} className="min-h-[60px] text-xs" />
                          <Button size="sm" className="w-full bg-gradient-to-r from-primary to-primary/90 text-xs" disabled={submittingReview} onClick={async () => {
                            if (!user?.id) return;
                            setSubmittingReview(true);
                            try {
                              const res = await fetch('/api/reviews', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ userId: user.id, rating: userRating, comment: reviewComment || null, reviewType: 'shop', referenceId: selectedShop.id }),
                              });
                              if (res.ok) {
                                toast({ title: language === 'bn' ? 'রিভিউ জমা হয়েছে!' : 'Review submitted!' });
                                setUserRating(0); setReviewComment('');
                                const reviewRes = await fetch(`/api/reviews?reviewType=shop&referenceId=${selectedShop.id}`);
                                const reviewData = await reviewRes.json();
                                if (reviewData.reviews) setShopReviews(reviewData);
                              }
                            } catch { toast({ title: 'Failed to submit review', variant: 'destructive' }); }
                            finally { setSubmittingReview(false); }
                          }}>
                            {submittingReview ? (language === 'bn' ? 'জমা হচ্ছে...' : 'Submitting...') : (language === 'bn' ? 'রিভিউ জমা দিন' : 'Submit Review')}
                          </Button>
                        </div>
                      )}
                    </div>
                  )}
                  {!isLoggedIn && <p className="mb-3 text-xs text-muted-foreground">{language === 'bn' ? 'রিভিউ দিতে লগইন করুন' : 'Login to leave a review'}</p>}
                  {shopReviews.reviews.length > 0 ? (
                    <div className="space-y-2 max-h-48 overflow-y-auto custom-scrollbar">
                      {shopReviews.reviews.map((review) => (
                        <div key={review.id} className="rounded-lg bg-muted/30 p-2.5">
                          <div className="flex items-center gap-2 mb-1">
                            <div className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10"><span className="text-[10px] font-bold text-primary">{review.userName.charAt(0)}</span></div>
                            <span className="text-xs font-medium">{review.userName}</span>
                            <div className="flex gap-0.5 ml-auto">{[1,2,3,4,5].map((s) => (<Star key={s} className={`h-2.5 w-2.5 ${s <= review.rating ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground/20'}`} />))}</div>
                          </div>
                          {review.comment && <p className="text-[11px] text-muted-foreground leading-relaxed">{review.comment}</p>}
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="text-xs text-muted-foreground text-center py-3">{language === 'bn' ? 'এখনো কোনো রিভিউ নেই' : 'No reviews yet'}</p>
                  )}
                </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 = getOwnerPhone(selectedShop);
                    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={() => {
                    const ownerName = getOwnerName(selectedShop);
                    setSelectedShopId(null);
                    setOpenChatWith({
                      id: getOwnerId(selectedShop) || `owner-${ownerName.toLowerCase().replace(/\s+/g, '-')}`,
                      name: 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>
  );
}
