'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { bangladeshDivisions } from '@/lib/mock-data';
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 {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
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,
  Plus,
  Home,
  Store,
  Building2,
  Eye,
  EyeOff,
  Edit3,
  Trash2,
  Upload,
  BarChart3,
  Phone,
  Bed,
  Bath,
  Maximize,
  Warehouse,
  ShoppingBag,
  Camera,
  Video,
  X,
  ImagePlus,
  Play,
} from 'lucide-react';

// ─── Interfaces ─────────────────────────────────────────────────
interface DbHouse {
  id: string;
  title: string;
  description: string;
  price: number;
  rooms: number;
  bathrooms: number | null;
  area: number | null;
  floor: string | null;
  houseType: string;
  rentType: string;
  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 };
}

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 };
}

// ─── File Validation Constants ────────────────────────────────────
const ALLOWED_PHOTO_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm'];
const MAX_PHOTO_SIZE = 5 * 1024 * 1024; // 5MB
const MAX_VIDEO_SIZE = 50 * 1024 * 1024; // 50MB
const MAX_PHOTOS = 10;
const MAX_VIDEOS = 3;

// ─── Media Upload Section (Reusable) ────────────────────────────
function MediaUploadSection({
  language,
  photos,
  photoPreviews,
  videos,
  videoPreviews,
  onAddPhotos,
  onAddVideos,
  onRemovePhoto,
  onRemoveVideo,
  photoInputRef,
  videoInputRef,
}: {
  language: 'en' | 'bn';
  photos: File[];
  photoPreviews: string[];
  videos: File[];
  videoPreviews: string[];
  onAddPhotos: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onAddVideos: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onRemovePhoto: (index: number) => void;
  onRemoveVideo: (index: number) => void;
  photoInputRef: React.RefObject<HTMLInputElement | null>;
  videoInputRef: React.RefObject<HTMLInputElement | null>;
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs font-medium">
        {language === 'en' ? 'Photos & Videos' : 'ছবি ও ভিডিও'}
      </Label>

      {/* Preview Grid */}
      {(photoPreviews.length > 0 || videoPreviews.length > 0) && (
        <div className="flex gap-2 overflow-x-auto pb-2 custom-scrollbar">
          {/* Photo Previews */}
          {photoPreviews.map((src, idx) => (
            <div
              key={`photo-${idx}`}
              className="relative h-16 w-16 shrink-0 overflow-hidden rounded-lg border bg-muted"
            >
              <img
                src={src}
                alt={`Photo ${idx + 1}`}
                className="h-full w-full object-cover"
              />
              <button
                type="button"
                onClick={() => onRemovePhoto(idx)}
                className="absolute -right-1 -top-1 flex h-4.5 w-4.5 items-center justify-center rounded-full bg-destructive text-white shadow-sm hover:bg-destructive/90"
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}

          {/* Video Previews */}
          {videoPreviews.map((src, idx) => (
            <div
              key={`video-${idx}`}
              className="relative h-16 w-16 shrink-0 overflow-hidden rounded-lg border bg-muted"
            >
              <video
                src={src}
                className="h-full w-full object-cover"
                muted
              />
              <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                <Play className="h-5 w-5 text-white" />
              </div>
              <button
                type="button"
                onClick={() => onRemoveVideo(idx)}
                className="absolute -right-1 -top-1 flex h-4.5 w-4.5 items-center justify-center rounded-full bg-destructive text-white shadow-sm hover:bg-destructive/90"
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}

          {/* Plus placeholder if under limits */}
          {photoPreviews.length + videoPreviews.length < MAX_PHOTOS + MAX_VIDEOS && (
            <button
              type="button"
              onClick={() => photoInputRef.current?.click()}
              className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/30 text-muted-foreground/50 hover:border-primary/40 hover:text-primary/60 transition-colors"
            >
              <ImagePlus className="h-5 w-5" />
            </button>
          )}
        </div>
      )}

      {/* Empty state with plus icon */}
      {photoPreviews.length === 0 && videoPreviews.length === 0 && (
        <button
          type="button"
          onClick={() => photoInputRef.current?.click()}
          className="flex w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-muted-foreground/25 py-6 text-muted-foreground/60 hover:border-primary/40 hover:text-primary/70 transition-colors"
        >
          <ImagePlus className="h-5 w-5" />
          <span className="text-xs font-medium">
            {language === 'en' ? 'Add photos & videos' : 'ছবি ও ভিডিও যোগ করুন'}
          </span>
        </button>
      )}

      {/* Upload Buttons Row */}
      <div className="flex gap-2">
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="flex-1 gap-1.5 text-[11px]"
          onClick={() => photoInputRef.current?.click()}
          disabled={photos.length >= MAX_PHOTOS}
        >
          <Camera className="h-3.5 w-3.5" />
          {language === 'en' ? 'Add Photos' : 'ছবি যোগ করুন'}
          <Badge variant="secondary" className="ml-1 h-4 px-1.5 text-[9px]">
            {photos.length}/{MAX_PHOTOS}
          </Badge>
        </Button>
        <Button
          type="button"
          variant="outline"
          size="sm"
          className="flex-1 gap-1.5 text-[11px]"
          onClick={() => videoInputRef.current?.click()}
          disabled={videos.length >= MAX_VIDEOS}
        >
          <Video className="h-3.5 w-3.5" />
          {language === 'en' ? 'Add Video' : 'ভিডিও যোগ করুন'}
          <Badge variant="secondary" className="ml-1 h-4 px-1.5 text-[9px]">
            {videos.length}/{MAX_VIDEOS}
          </Badge>
        </Button>
      </div>

      {/* Hidden File Inputs */}
      <input
        ref={photoInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        multiple
        className="hidden"
        onChange={onAddPhotos}
      />
      <input
        ref={videoInputRef}
        type="file"
        accept="video/mp4,video/webm"
        multiple
        className="hidden"
        onChange={onAddVideos}
      />

      <p className="text-[10px] text-muted-foreground">
        {language === 'en'
          ? `Max ${MAX_PHOTOS} photos (5MB each, JPG/PNG/WebP) & ${MAX_VIDEOS} videos (50MB each, MP4/WebM)`
          : `সর্বোচ্চ ${MAX_PHOTOS} টি ছবি (প্রতিটি ৫এমবি, JPG/PNG/WebP) এবং ${MAX_VIDEOS} টি ভিডিও (প্রতিটি ৫০এমবি, MP4/WebM)`}
      </p>
    </div>
  );
}

// ─── House Upload Form ──────────────────────────────────────────
function HouseUploadForm({
  language,
  ownerId,
  onSaved,
  editHouse,
  onCancelEdit,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onSaved: () => void;
  editHouse: DbHouse | null;
  onCancelEdit: () => void;
}) {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);

  // Media upload state
  const [photos, setPhotos] = useState<File[]>([]);
  const [videos, setVideos] = useState<File[]>([]);
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([]);
  const [videoPreviews, setVideoPreviews] = useState<string[]>([]);
  const photoInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);

  // Cleanup object URLs on unmount
  useEffect(() => {
    return () => {
      photoPreviews.forEach((url) => URL.revokeObjectURL(url));
      videoPreviews.forEach((url) => URL.revokeObjectURL(url));
    };
  }, []);

  const handleAddPhotos = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const validFiles: File[] = [];
    const newPreviews: string[] = [];

    for (const file of files) {
      if (!ALLOWED_PHOTO_TYPES.includes(file.type)) {
        toast({
          title: language === 'en' ? `"${file.name}" is not a valid image type. Use JPG, PNG, or WebP.` : `"${file.name}" বৈধ ছবি ফরম্যাট নয়। JPG, PNG, বা WebP ব্যবহার করুন।`,
          variant: 'destructive',
        });
        continue;
      }
      if (file.size > MAX_PHOTO_SIZE) {
        toast({
          title: language === 'en' ? `"${file.name}" exceeds 5MB limit.` : `"${file.name}" ৫এমবি সীমা অতিক্রম করেছে।`,
          variant: 'destructive',
        });
        continue;
      }
      validFiles.push(file);
      newPreviews.push(URL.createObjectURL(file));
    }

    const remaining = MAX_PHOTOS - photos.length;
    const toAdd = validFiles.slice(0, remaining);
    const toAddPreviews = newPreviews.slice(0, remaining);

    if (validFiles.length > remaining) {
      toast({
        title: language === 'en' ? `Only ${remaining} more photo(s) can be added (max ${MAX_PHOTOS})` : `আর মাত্র ${remaining} টি ছবি যোগ করা যাবে (সর্বোচ্চ ${MAX_PHOTOS})`,
        variant: 'destructive',
      });
    }

    setPhotos((prev) => [...prev, ...toAdd]);
    setPhotoPreviews((prev) => [...prev, ...toAddPreviews]);
    e.target.value = '';
  };

  const handleAddVideos = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const validFiles: File[] = [];
    const newPreviews: string[] = [];

    for (const file of files) {
      if (!ALLOWED_VIDEO_TYPES.includes(file.type)) {
        toast({
          title: language === 'en' ? `"${file.name}" is not a valid video type. Use MP4 or WebM.` : `"${file.name}" বৈধ ভিডিও ফরম্যাট নয়। MP4 বা WebM ব্যবহার করুন।`,
          variant: 'destructive',
        });
        continue;
      }
      if (file.size > MAX_VIDEO_SIZE) {
        toast({
          title: language === 'en' ? `"${file.name}" exceeds 50MB limit.` : `"${file.name}" ৫০এমবি সীমা অতিক্রম করেছে।`,
          variant: 'destructive',
        });
        continue;
      }
      validFiles.push(file);
      newPreviews.push(URL.createObjectURL(file));
    }

    const remaining = MAX_VIDEOS - videos.length;
    const toAdd = validFiles.slice(0, remaining);
    const toAddPreviews = newPreviews.slice(0, remaining);

    if (validFiles.length > remaining) {
      toast({
        title: language === 'en' ? `Only ${remaining} more video(s) can be added (max ${MAX_VIDEOS})` : `আর মাত্র ${remaining} টি ভিডিও যোগ করা যাবে (সর্বোচ্চ ${MAX_VIDEOS})`,
        variant: 'destructive',
      });
    }

    setVideos((prev) => [...prev, ...toAdd]);
    setVideoPreviews((prev) => [...prev, ...toAddPreviews]);
    e.target.value = '';
  };

  const handleRemovePhoto = (index: number) => {
    URL.revokeObjectURL(photoPreviews[index]);
    setPhotos((prev) => prev.filter((_, i) => i !== index));
    setPhotoPreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const handleRemoveVideo = (index: number) => {
    URL.revokeObjectURL(videoPreviews[index]);
    setVideos((prev) => prev.filter((_, i) => i !== index));
    setVideoPreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const clearMediaState = () => {
    photoPreviews.forEach((url) => URL.revokeObjectURL(url));
    videoPreviews.forEach((url) => URL.revokeObjectURL(url));
    setPhotos([]);
    setVideos([]);
    setPhotoPreviews([]);
    setVideoPreviews([]);
  };

  const [form, setForm] = useState({
    title: editHouse?.title || '',
    description: editHouse?.description || '',
    price: editHouse?.price?.toString() || '',
    rooms: editHouse?.rooms?.toString() || '',
    bathrooms: editHouse?.bathrooms?.toString() || '',
    area: editHouse?.area?.toString() || '',
    floor: editHouse?.floor || '',
    houseType: editHouse?.houseType || 'flat',
    rentType: editHouse?.rentType || 'both',
    contactNumber: '',
    address: editHouse?.address || '',
    division: editHouse?.division || '',
    district: editHouse?.district || '',
    upazila: editHouse?.upazila || '',
  });

  useEffect(() => {
    if (editHouse) {
      setForm({
        title: editHouse.title,
        description: editHouse.description,
        price: editHouse.price.toString(),
        rooms: editHouse.rooms.toString(),
        bathrooms: editHouse.bathrooms?.toString() || '',
        area: editHouse.area?.toString() || '',
        floor: editHouse.floor || '',
        houseType: editHouse.houseType,
        rentType: editHouse.rentType,
        contactNumber: editHouse.owner?.phone || '',
        address: editHouse.address,
        division: editHouse.division,
        district: editHouse.district,
        upazila: editHouse.upazila || '',
      });
    }
  }, [editHouse]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (
      !form.title ||
      !form.description ||
      !form.price ||
      !form.rooms ||
      !form.address ||
      !form.division ||
      !form.district
    ) {
      toast({
        title: language === 'en' ? 'Please fill all required fields' : 'সকল প্রয়োজনীয় ক্ষেত্র পূরণ করুন',
        variant: 'destructive',
      });
      return;
    }

    setIsLoading(true);
    try {
      if (editHouse) {
        const res = await fetch('/api/houses', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            id: editHouse.id,
            ...form,
            price: parseFloat(form.price),
            rooms: parseInt(form.rooms),
            bathrooms: form.bathrooms ? parseInt(form.bathrooms) : null,
            area: form.area ? parseFloat(form.area) : null,
            images: photoPreviews.join(','),
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: t('house.updateSuccess', language) });
          clearMediaState();
          onSaved();
          onCancelEdit();
        } else {
          toast({
            title: data.error || (language === 'en' ? 'Failed to update' : 'আপডেট ব্যর্থ'),
            variant: 'destructive',
          });
        }
      } else {
        const res = await fetch('/api/houses', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...form,
            price: parseFloat(form.price),
            rooms: parseInt(form.rooms),
            bathrooms: form.bathrooms ? parseInt(form.bathrooms) : null,
            area: form.area ? parseFloat(form.area) : null,
            ownerId,
            images: photoPreviews.join(','),
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({ title: t('house.postSuccess', language) });
          onSaved();
          clearMediaState();
          setForm({
            title: '',
            description: '',
            price: '',
            rooms: '',
            bathrooms: '',
            area: '',
            floor: '',
            houseType: 'flat',
            rentType: 'both',
            contactNumber: '',
            address: '',
            division: '',
            district: '',
            upazila: '',
          });
        } else {
          toast({
            title: data.error || (language === 'en' ? 'Failed to post' : 'পোস্ট ব্যর্থ'),
            variant: 'destructive',
          });
        }
      }
    } catch {
      toast({
        title: language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

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

      {/* Title */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">{t('house.houseTitle', language)} *</Label>
        <Input
          value={form.title}
          onChange={(e) => setForm({ ...form, title: e.target.value })}
          placeholder={language === 'en' ? 'e.g. 3BHK Flat in Dhanmondi' : 'যেমন: ধানমন্ডিতে ৩ বেডরুম ফ্ল্যাট'}
          className="text-sm"
          required
        />
      </div>

      {/* Photos & Videos */}
      <MediaUploadSection
        language={language}
        photos={photos}
        photoPreviews={photoPreviews}
        videos={videos}
        videoPreviews={videoPreviews}
        onAddPhotos={handleAddPhotos}
        onAddVideos={handleAddVideos}
        onRemovePhoto={handleRemovePhoto}
        onRemoveVideo={handleRemoveVideo}
        photoInputRef={photoInputRef}
        videoInputRef={videoInputRef}
      />

      {/* Description */}
      <div className="space-y-1.5">
        <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 house...' : 'আপনার বাড়ির বিবরণ...'}
          className="min-h-[80px] text-sm"
          required
        />
      </div>

      {/* House Type & Rent Type */}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.houseType', language)} *</Label>
          <select
            value={form.houseType}
            onChange={(e) => setForm({ ...form, houseType: e.target.value })}
            className="w-full rounded-md border bg-background px-3 py-2 text-sm"
          >
            <option value="flat">{t('house.flat', language)}</option>
            <option value="house">{t('house.house', language)}</option>
            <option value="room">{t('house.room', language)}</option>
            <option value="mess">{t('house.mess', language)}</option>
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.rentType', language)} *</Label>
          <select
            value={form.rentType}
            onChange={(e) => setForm({ ...form, rentType: e.target.value })}
            className="w-full rounded-md border bg-background px-3 py-2 text-sm"
          >
            <option value="family">{t('house.family', language)}</option>
            <option value="bachelor">{t('house.bachelor', language)}</option>
            <option value="both">{t('house.both', language)}</option>
          </select>
        </div>
      </div>

      {/* Price & Floor */}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <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="text-sm"
            required
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.floorNo', language)}</Label>
          <Input
            value={form.floor}
            onChange={(e) => setForm({ ...form, floor: e.target.value })}
            placeholder={language === 'en' ? 'e.g. 4th' : 'যেমন: ৪র্থ'}
            className="text-sm"
          />
        </div>
      </div>

      {/* Rooms, Bathrooms, Area */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.noBedrooms', language)} *</Label>
          <Input
            type="number"
            value={form.rooms}
            onChange={(e) => setForm({ ...form, rooms: e.target.value })}
            placeholder="3"
            className="text-sm"
            required
            min="1"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.noBathrooms', language)}</Label>
          <Input
            type="number"
            value={form.bathrooms}
            onChange={(e) => setForm({ ...form, bathrooms: e.target.value })}
            placeholder="2"
            className="text-sm"
            min="0"
          />
        </div>
        <div className="space-y-1.5">
          <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="1200"
            className="text-sm"
            min="0"
          />
        </div>
      </div>

      <Separator />

      {/* Contact Number */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">
          <span className="flex items-center gap-1">
            <Phone className="h-3 w-3" />
            {language === 'en' ? 'Contact Number' : 'যোগাযোগ নম্বর'}
          </span>
        </Label>
        <Input
          type="tel"
          value={form.contactNumber}
          onChange={(e) => setForm({ ...form, contactNumber: e.target.value })}
          placeholder={language === 'en' ? '+8801XXXXXXXXX' : '+8801XXXXXXXXX'}
          className="text-sm"
        />
      </div>

      {/* Address */}
      <div className="space-y-1.5">
        <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' ? 'House 12, Road 27, Dhanmondi' : 'বাড়ি ১২, রোড ২৭, ধানমন্ডি'}
          className="text-sm"
          required
        />
      </div>

      {/* Division, District, Upazila */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.division', language)} *</Label>
          <select
            value={form.division}
            onChange={(e) => setForm({ ...form, division: e.target.value })}
            className="w-full rounded-md border bg-background px-2 py-2 text-sm"
            required
          >
            <option value="">{language === 'en' ? 'Select' : 'নির্বাচন'}</option>
            {bangladeshDivisions.map((d) => (
              <option key={d} value={d}>
                {d}
              </option>
            ))}
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.district', language)} *</Label>
          <Input
            value={form.district}
            onChange={(e) => setForm({ ...form, district: e.target.value })}
            placeholder={language === 'en' ? 'Dhaka' : 'ঢাকা'}
            className="text-sm"
            required
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.upazila', language)}</Label>
          <Input
            value={form.upazila}
            onChange={(e) => setForm({ ...form, upazila: e.target.value })}
            placeholder={language === 'en' ? 'Dhanmondi' : 'ধানমন্ডি'}
            className="text-sm"
          />
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex gap-3 pt-2">
        {editHouse && (
          <Button type="button" variant="outline" className="flex-1" onClick={onCancelEdit}>
            {t('common.cancel', language)}
          </Button>
        )}
        <Button
          type="submit"
          className="flex-1 bg-gradient-to-r from-primary to-primary/90 font-semibold"
          disabled={isLoading}
        >
          {isLoading
            ? t('common.loading', language)
            : editHouse
              ? t('common.save', language)
              : t('house.postHouse', language)}
        </Button>
      </div>
    </form>
  );
}

// ─── Shop Upload Form ───────────────────────────────────────────
function ShopUploadForm({
  language,
  ownerId,
  onSaved,
  editShop,
  onCancelEdit,
}: {
  language: 'en' | 'bn';
  ownerId: string;
  onSaved: () => void;
  editShop: DbShop | null;
  onCancelEdit: () => void;
}) {
  const { toast } = useToast();
  const [isLoading, setIsLoading] = useState(false);

  // Media upload state
  const [photos, setPhotos] = useState<File[]>([]);
  const [videos, setVideos] = useState<File[]>([]);
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([]);
  const [videoPreviews, setVideoPreviews] = useState<string[]>([]);
  const photoInputRef = useRef<HTMLInputElement>(null);
  const videoInputRef = useRef<HTMLInputElement>(null);

  // Cleanup object URLs on unmount
  useEffect(() => {
    return () => {
      photoPreviews.forEach((url) => URL.revokeObjectURL(url));
      videoPreviews.forEach((url) => URL.revokeObjectURL(url));
    };
  }, []);

  const handleAddPhotos = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const validFiles: File[] = [];
    const newPreviews: string[] = [];

    for (const file of files) {
      if (!ALLOWED_PHOTO_TYPES.includes(file.type)) {
        toast({
          title: language === 'en' ? `"${file.name}" is not a valid image type. Use JPG, PNG, or WebP.` : `"${file.name}" বৈধ ছবি ফরম্যাট নয়। JPG, PNG, বা WebP ব্যবহার করুন।`,
          variant: 'destructive',
        });
        continue;
      }
      if (file.size > MAX_PHOTO_SIZE) {
        toast({
          title: language === 'en' ? `"${file.name}" exceeds 5MB limit.` : `"${file.name}" ৫এমবি সীমা অতিক্রম করেছে।`,
          variant: 'destructive',
        });
        continue;
      }
      validFiles.push(file);
      newPreviews.push(URL.createObjectURL(file));
    }

    const remaining = MAX_PHOTOS - photos.length;
    const toAdd = validFiles.slice(0, remaining);
    const toAddPreviews = newPreviews.slice(0, remaining);

    if (validFiles.length > remaining) {
      toast({
        title: language === 'en' ? `Only ${remaining} more photo(s) can be added (max ${MAX_PHOTOS})` : `আর মাত্র ${remaining} টি ছবি যোগ করা যাবে (সর্বোচ্চ ${MAX_PHOTOS})`,
        variant: 'destructive',
      });
    }

    setPhotos((prev) => [...prev, ...toAdd]);
    setPhotoPreviews((prev) => [...prev, ...toAddPreviews]);
    e.target.value = '';
  };

  const handleAddVideos = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    const validFiles: File[] = [];
    const newPreviews: string[] = [];

    for (const file of files) {
      if (!ALLOWED_VIDEO_TYPES.includes(file.type)) {
        toast({
          title: language === 'en' ? `"${file.name}" is not a valid video type. Use MP4 or WebM.` : `"${file.name}" বৈধ ভিডিও ফরম্যাট নয়। MP4 বা WebM ব্যবহার করুন।`,
          variant: 'destructive',
        });
        continue;
      }
      if (file.size > MAX_VIDEO_SIZE) {
        toast({
          title: language === 'en' ? `"${file.name}" exceeds 50MB limit.` : `"${file.name}" ৫০এমবি সীমা অতিক্রম করেছে।`,
          variant: 'destructive',
        });
        continue;
      }
      validFiles.push(file);
      newPreviews.push(URL.createObjectURL(file));
    }

    const remaining = MAX_VIDEOS - videos.length;
    const toAdd = validFiles.slice(0, remaining);
    const toAddPreviews = newPreviews.slice(0, remaining);

    if (validFiles.length > remaining) {
      toast({
        title: language === 'en' ? `Only ${remaining} more video(s) can be added (max ${MAX_VIDEOS})` : `আর মাত্র ${remaining} টি ভিডিও যোগ করা যাবে (সর্বোচ্চ ${MAX_VIDEOS})`,
        variant: 'destructive',
      });
    }

    setVideos((prev) => [...prev, ...toAdd]);
    setVideoPreviews((prev) => [...prev, ...toAddPreviews]);
    e.target.value = '';
  };

  const handleRemovePhoto = (index: number) => {
    URL.revokeObjectURL(photoPreviews[index]);
    setPhotos((prev) => prev.filter((_, i) => i !== index));
    setPhotoPreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const handleRemoveVideo = (index: number) => {
    URL.revokeObjectURL(videoPreviews[index]);
    setVideos((prev) => prev.filter((_, i) => i !== index));
    setVideoPreviews((prev) => prev.filter((_, i) => i !== index));
  };

  const clearMediaState = () => {
    photoPreviews.forEach((url) => URL.revokeObjectURL(url));
    videoPreviews.forEach((url) => URL.revokeObjectURL(url));
    setPhotos([]);
    setVideos([]);
    setPhotoPreviews([]);
    setVideoPreviews([]);
  };

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

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.title || !form.description || !form.price || !form.address || !form.division || !form.district) {
      toast({
        title: language === 'en' ? '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,
            ...form,
            price: parseFloat(form.price),
            area: form.area ? parseFloat(form.area) : null,
            images: photoPreviews.join(','),
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({
            title: language === 'en' ? 'Shop updated successfully!' : 'দোকান সফলভাবে আপডেট হয়েছে!',
          });
          clearMediaState();
          onSaved();
          onCancelEdit();
        } else {
          toast({
            title: data.error || (language === 'en' ? 'Failed to update' : 'আপডেট ব্যর্থ'),
            variant: 'destructive',
          });
        }
      } else {
        const res = await fetch('/api/shops', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...form,
            price: parseFloat(form.price),
            area: form.area ? parseFloat(form.area) : null,
            ownerId,
            images: photoPreviews.join(','),
          }),
        });
        const data = await res.json();
        if (res.ok) {
          toast({
            title: language === 'en' ? 'Shop posted successfully!' : 'দোকান সফলভাবে পোস্ট হয়েছে!',
          });
          onSaved();
          clearMediaState();
          setForm({
            title: '',
            description: '',
            price: '',
            shopType: 'commercial',
            area: '',
            contactNumber: '',
            address: '',
            division: '',
            district: '',
            upazila: '',
          });
        } else {
          toast({
            title: data.error || (language === 'en' ? 'Failed to post' : 'পোস্ট ব্যর্থ'),
            variant: 'destructive',
          });
        }
      }
    } catch {
      toast({
        title: language === 'en' ? 'Network error' : 'নেটওয়ার্ক ত্রুটি',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

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

      {/* Title */}
      <div className="space-y-1.5">
        <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 Shop in New Market' : 'যেমন: নিউ মার্কেটে কমার্শিয়াল দোকান'}
          className="text-sm"
          required
        />
      </div>

      {/* Photos & Videos */}
      <MediaUploadSection
        language={language}
        photos={photos}
        photoPreviews={photoPreviews}
        videos={videos}
        videoPreviews={videoPreviews}
        onAddPhotos={handleAddPhotos}
        onAddVideos={handleAddVideos}
        onRemovePhoto={handleRemovePhoto}
        onRemoveVideo={handleRemoveVideo}
        photoInputRef={photoInputRef}
        videoInputRef={videoInputRef}
      />

      {/* Description */}
      <div className="space-y-1.5">
        <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-[80px] text-sm"
          required
        />
      </div>

      {/* Shop Type & Monthly Rent */}
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <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-3 py-2 text-sm"
          >
            <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.5">
          <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="40000"
            className="text-sm"
            required
          />
        </div>
      </div>

      {/* Area */}
      <div className="space-y-1.5">
        <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="500"
          className="text-sm"
          min="0"
        />
      </div>

      <Separator />

      {/* Contact Number */}
      <div className="space-y-1.5">
        <Label className="text-xs font-medium">
          <span className="flex items-center gap-1">
            <Phone className="h-3 w-3" />
            {language === 'en' ? 'Contact Number' : 'যোগাযোগ নম্বর'}
          </span>
        </Label>
        <Input
          type="tel"
          value={form.contactNumber}
          onChange={(e) => setForm({ ...form, contactNumber: e.target.value })}
          placeholder="+8801XXXXXXXXX"
          className="text-sm"
        />
      </div>

      {/* Address */}
      <div className="space-y-1.5">
        <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' ? 'New Market, Dhaka' : 'নিউ মার্কেট, ঢাকা'}
          className="text-sm"
          required
        />
      </div>

      {/* Division, District, Upazila */}
      <div className="grid grid-cols-3 gap-3">
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.division', language)} *</Label>
          <select
            value={form.division}
            onChange={(e) => setForm({ ...form, division: e.target.value })}
            className="w-full rounded-md border bg-background px-2 py-2 text-sm"
            required
          >
            <option value="">{language === 'en' ? 'Select' : 'নির্বাচন'}</option>
            {bangladeshDivisions.map((d) => (
              <option key={d} value={d}>
                {d}
              </option>
            ))}
          </select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.district', language)} *</Label>
          <Input
            value={form.district}
            onChange={(e) => setForm({ ...form, district: e.target.value })}
            placeholder={language === 'en' ? 'Dhaka' : 'ঢাকা'}
            className="text-sm"
            required
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs font-medium">{t('house.upazila', language)}</Label>
          <Input
            value={form.upazila}
            onChange={(e) => setForm({ ...form, upazila: e.target.value })}
            placeholder={language === 'en' ? 'New Market' : 'নিউ মার্কেট'}
            className="text-sm"
          />
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex gap-3 pt-2">
        {editShop && (
          <Button type="button" variant="outline" className="flex-1" onClick={onCancelEdit}>
            {t('common.cancel', language)}
          </Button>
        )}
        <Button
          type="submit"
          className="flex-1 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>
  );
}

// ─── Main Owner Dashboard Module ────────────────────────────────
export default function OwnerDashboardModule() {
  const { language, isLoggedIn, user, setCurrentSection } = useAppStore();
  const { toast } = useToast();

  const [houses, setHouses] = useState<DbHouse[]>([]);
  const [shops, setShops] = useState<DbShop[]>([]);
  const [housesLoading, setHousesLoading] = useState(true);
  const [shopsLoading, setShopsLoading] = useState(true);
  const [uploadChoiceOpen, setUploadChoiceOpen] = useState(false);
  const [houseFormOpen, setHouseFormOpen] = useState(false);
  const [shopFormOpen, setShopFormOpen] = useState(false);
  const [editingHouse, setEditingHouse] = useState<DbHouse | null>(null);
  const [editingShop, setEditingShop] = useState<DbShop | null>(null);

  // Determine default tab based on user roles
  const isHouseOwner = user?.roles?.includes('houseOwner') ?? false;
  const isShopOwner = user?.roles?.includes('shopOwner') ?? false;
  const defaultTab = isShopOwner && !isHouseOwner ? 'shops' : 'houses';

  const [activeTab, setActiveTab] = useState(defaultTab);

  // Fetch owner's houses
  const fetchMyHouses = useCallback(async () => {
    if (!user?.id) return;
    try {
      setHousesLoading(true);
      const res = await fetch(`/api/houses/my?ownerId=${user.id}`);
      const data = await res.json();
      if (data.houses) setHouses(data.houses);
    } catch (err) {
      console.error('Failed to fetch my houses:', err);
    } finally {
      setHousesLoading(false);
    }
  }, [user?.id]);

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

  useEffect(() => {
    if (isLoggedIn && user?.id) {
      fetchMyHouses();
      fetchMyShops();
    }
  }, [isLoggedIn, user?.id, fetchMyHouses, fetchMyShops]);

  // Toggle house availability
  const handleToggleHouseAvailable = async (houseId: string, current: boolean) => {
    try {
      const res = await fetch('/api/houses', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: houseId, isAvailable: !current }),
      });
      if (res.ok) {
        toast({
          title: current
            ? (language === 'en' ? 'Marked as rented' : 'ভাড়া হয়েছে চিহ্নিত')
            : t('house.availableNow', language),
        });
        fetchMyHouses();
      }
    } catch (err) {
      console.error('Failed to toggle house availability:', err);
    }
  };

  // Delete house
  const handleDeleteHouse = async (houseId: string) => {
    try {
      const res = await fetch('/api/houses', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: houseId }),
      });
      if (res.ok) {
        toast({ title: t('house.deleteSuccess', language) });
        fetchMyHouses();
      }
    } catch (err) {
      console.error('Failed to delete house:', err);
    }
  };

  // Toggle shop availability
  const handleToggleShopAvailable = 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' ? 'Available Now' : 'এখন খালি'),
        });
        fetchMyShops();
      }
    } catch (err) {
      console.error('Failed to toggle shop availability:', err);
    }
  };

  // Delete shop
  const handleDeleteShop = 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 successfully!' : 'দোকান সফলভাবে মুছে ফেলা হয়েছে!',
        });
        fetchMyShops();
      }
    } catch (err) {
      console.error('Failed to delete shop:', err);
    }
  };

  // Open upload choice
  const handleUploadClick = () => {
    if (isHouseOwner && !isShopOwner) {
      setEditingHouse(null);
      setHouseFormOpen(true);
    } else if (isShopOwner && !isHouseOwner) {
      setEditingShop(null);
      setShopFormOpen(true);
    } else {
      setUploadChoiceOpen(true);
    }
  };

  // Stats
  const activeHouseCount = houses.filter((h) => h.isAvailable).length;
  const activeShopCount = shops.filter((s) => s.isAvailable).length;
  const totalActive = activeHouseCount + activeShopCount;

  // Get house type gradient
  const getHouseTypeGradient = (houseType: string) => {
    switch (houseType) {
      case 'flat':
        return 'from-orange-400 to-amber-500';
      case 'house':
        return 'from-orange-500 to-red-500';
      case 'room':
        return 'from-amber-400 to-orange-500';
      case 'mess':
        return 'from-yellow-400 to-orange-400';
      default:
        return 'from-orange-400 to-amber-500';
    }
  };

  // Get shop type gradient
  const getShopTypeGradient = (shopType: string) => {
    switch (shopType) {
      case 'commercial':
        return 'from-amber-400 to-orange-500';
      case 'office':
        return 'from-primary to-primary/90';
      case 'warehouse':
        return 'from-slate-400 to-gray-500';
      case 'retail':
        return 'from-orange-400 to-amber-500';
      default:
        return 'from-amber-400 to-orange-500';
    }
  };

  // Get shop type label
  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;
    }
  };

  // Get house type icon
  const getHouseTypeIcon = (houseType: string) => {
    switch (houseType) {
      case 'flat':
        return Building2;
      case 'house':
        return Home;
      case 'room':
        return Bed;
      case 'mess':
        return Building2;
      default:
        return Building2;
    }
  };

  // Get shop type icon
  const getShopTypeIcon = (shopType: string) => {
    switch (shopType) {
      case 'commercial':
        return Store;
      case 'office':
        return Building2;
      case 'warehouse':
        return Warehouse;
      case 'retail':
        return ShoppingBag;
      default:
        return Store;
    }
  };

  // ─── Not logged in state ──────────────────────────────────────
  if (!isLoggedIn || !user) {
    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">
              {language === 'en' ? 'Owner Dashboard' : 'মালিক ড্যাশবোর্ড'}
            </h1>
          </div>
        </div>
        <div className="flex flex-1 flex-col items-center justify-center gap-4 px-4 py-16">
          <div className="flex h-20 w-20 items-center justify-center rounded-2xl bg-primary/10">
            <Building2 className="h-10 w-10 text-primary/40" />
          </div>
          <p className="text-center text-sm text-muted-foreground">
            {language === 'en'
              ? 'Please login to access your owner dashboard'
              : 'আপনার মালিক ড্যাশবোর্ড অ্যাক্সেস করতে লগইন করুন'}
          </p>
          <Button
            className="bg-gradient-to-r from-primary to-primary/90 font-semibold"
            onClick={() => setCurrentSection('auth')}
          >
            {language === 'en' ? 'Login Now' : 'এখন লগইন করুন'}
          </Button>
        </div>
      </div>
    );
  }

  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">
            {language === 'en' ? 'Owner Dashboard' : 'মালিক ড্যাশবোর্ড'}
          </h1>
          <div className="ml-auto flex items-center gap-2">
            <Badge variant="outline" className="text-[10px]">
              {user.roles?.map((r) =>
                r === 'houseOwner'
                  ? (language === 'en' ? 'House Owner' : 'বাড়ির মালিক')
                  : r === 'shopOwner'
                    ? (language === 'en' ? 'Shop Owner' : 'দোকান মালিক')
                    : null
              ).filter(Boolean).join(' · ')}
            </Badge>
          </div>
        </div>
      </div>

      {/* ─── Content ─────────────────────────────────────────────── */}
      <div className="flex-1 px-4 py-4 space-y-4">
        {/* ─── Stats Cards ──────────────────────────────────────── */}
        <div className="grid grid-cols-2 gap-3">
          <Card className="overflow-hidden border-0 bg-gradient-to-br from-primary to-primary/80 text-primary-foreground">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20">
                  <Home className="h-5 w-5" />
                </div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">
                    {language === 'en' ? 'My Houses' : 'আমার বাড়ি'}
                  </p>
                  <p className="text-xl font-bold">{houses.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="overflow-hidden border-0 bg-gradient-to-br from-emerald-500 to-emerald-600/80 text-white">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20">
                  <Store className="h-5 w-5" />
                </div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">
                    {language === 'en' ? 'My Shops' : 'আমার দোকান'}
                  </p>
                  <p className="text-xl font-bold">{shops.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="overflow-hidden border-0 bg-gradient-to-br from-amber-500 to-amber-600/80 text-white">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20">
                  <Eye className="h-5 w-5" />
                </div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">
                    {language === 'en' ? 'Total Views' : 'মোট ভিউ'}
                  </p>
                  <p className="text-xl font-bold">0</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="overflow-hidden border-0 bg-gradient-to-br from-primary to-primary/80 text-white">
            <CardContent className="p-4">
              <div className="flex items-center gap-2">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/20">
                  <BarChart3 className="h-5 w-5" />
                </div>
                <div>
                  <p className="text-[10px] font-medium opacity-80">
                    {language === 'en' ? 'Active Listings' : 'সক্রিয় তালিকা'}
                  </p>
                  <p className="text-xl font-bold">{totalActive}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* ─── Upload Button ────────────────────────────────────── */}
        <Button
          className="w-full bg-gradient-to-r from-primary to-primary/90 font-semibold py-5 text-sm"
          size="lg"
          onClick={handleUploadClick}
        >
          <Upload className="mr-2 h-5 w-5" />
          {language === 'en' ? 'Upload New Listing' : 'নতুন তালিকা আপলোড করুন'}
        </Button>

        {/* ─── Tabs: My Houses & My Shops ────────────────────────── */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="houses" className="gap-1.5 text-xs">
              <Home className="h-3.5 w-3.5" />
              {language === 'en' ? 'My Houses' : 'আমার বাড়ি'}
              <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-[10px]">
                {houses.length}
              </Badge>
            </TabsTrigger>
            <TabsTrigger value="shops" className="gap-1.5 text-xs">
              <Store className="h-3.5 w-3.5" />
              {language === 'en' ? 'My Shops' : 'আমার দোকান'}
              <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-[10px]">
                {shops.length}
              </Badge>
            </TabsTrigger>
          </TabsList>

          {/* ─── My Houses Tab ─────────────────────────────────── */}
          <TabsContent value="houses" className="mt-4">
            {housesLoading ? (
              <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>
            ) : houses.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">
                    <Home className="h-8 w-8 text-primary/40" />
                  </div>
                  <p className="text-sm text-muted-foreground">
                    {language === 'en'
                      ? 'No houses listed yet'
                      : 'এখনো কোনো বাড়ি তালিকাভুক্ত নেই'}
                  </p>
                  <Button
                    size="sm"
                    variant="outline"
                    className="gap-1"
                    onClick={() => {
                      setEditingHouse(null);
                      setHouseFormOpen(true);
                    }}
                  >
                    <Plus className="h-4 w-4" />
                    {t('house.postHouse', language)}
                  </Button>
                </CardContent>
              </Card>
            ) : (
              <div className="grid gap-3 grid-cols-1 sm:grid-cols-2">
                {houses.map((house) => {
                  const HouseIcon = getHouseTypeIcon(house.houseType);
                  return (
                    <Card
                      key={house.id}
                      className="overflow-hidden transition-shadow hover:shadow-md"
                    >
                      <div
                        className={`relative flex h-28 items-center justify-center bg-gradient-to-br ${getHouseTypeGradient(house.houseType)}`}
                      >
                        <HouseIcon className="h-12 w-12 text-white/30" />
                        <Badge
                          className={`absolute left-3 top-3 text-[10px] ${
                            house.isAvailable
                              ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                              : 'bg-red-500 text-white hover:bg-red-600'
                          }`}
                        >
                          {house.isAvailable
                            ? t('house.availableNow', language)
                            : (language === 'en' ? 'Rented' : 'ভাড়া হয়েছে')}
                        </Badge>
                      </div>
                      <CardContent className="p-3">
                        <h3 className="truncate text-sm font-semibold">{house.title}</h3>
                        <div className="mt-1 flex items-center gap-2">
                          <span className="text-base font-bold text-primary">
                            ৳{house.price.toLocaleString()}
                          </span>
                          <span className="text-[10px] text-muted-foreground">
                            {t('house.perMonth', language)}
                          </span>
                        </div>
                        <div className="mt-1 flex items-center gap-2 text-[10px] text-muted-foreground">
                          <span className="flex items-center gap-0.5">
                            <Bed className="h-3 w-3" />
                            {house.rooms}
                          </span>
                          <span className="flex items-center gap-0.5">
                            <Bath className="h-3 w-3" />
                            {house.bathrooms || '-'}
                          </span>
                          {house.area && (
                            <span className="flex items-center gap-0.5">
                              <Maximize className="h-3 w-3" />
                              {house.area} sqft
                            </span>
                          )}
                        </div>
                        <div className="mt-3 flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            className="flex-1 text-[11px]"
                            onClick={() =>
                              handleToggleHouseAvailable(house.id, house.isAvailable)
                            }
                          >
                            {house.isAvailable ? (
                              <>
                                <EyeOff className="mr-1 h-3 w-3" />
                                {t('house.markRented', language)}
                              </>
                            ) : (
                              <>
                                <Eye className="mr-1 h-3 w-3" />
                                {t('house.availableNow', language)}
                              </>
                            )}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            className="text-[11px]"
                            onClick={() => {
                              setEditingHouse(house);
                              setHouseFormOpen(true);
                            }}
                          >
                            <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 "${house.title}".`
                                    : `এটি "${house.title}" স্থায়ীভাবে মুছে ফেলবে।`}
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter>
                                <AlertDialogCancel>
                                  {t('common.cancel', language)}
                                </AlertDialogCancel>
                                <AlertDialogAction
                                  className="bg-destructive text-destructive-foreground"
                                  onClick={() => handleDeleteHouse(house.id)}
                                >
                                  {t('common.delete', language)}
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            )}
          </TabsContent>

          {/* ─── My Shops Tab ──────────────────────────────────── */}
          <TabsContent value="shops" className="mt-4">
            {shopsLoading ? (
              <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>
            ) : 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-emerald-500/10">
                    <Store className="h-8 w-8 text-emerald-500/40" />
                  </div>
                  <p className="text-sm text-muted-foreground">
                    {language === 'en'
                      ? 'No shops listed yet'
                      : 'এখনো কোনো দোকান তালিকাভুক্ত নেই'}
                  </p>
                  <Button
                    size="sm"
                    variant="outline"
                    className="gap-1"
                    onClick={() => {
                      setEditingShop(null);
                      setShopFormOpen(true);
                    }}
                  >
                    <Plus className="h-4 w-4" />
                    {language === 'en' ? 'Post Shop' : 'দোকান পোস্ট করুন'}
                  </Button>
                </CardContent>
              </Card>
            ) : (
              <div className="grid gap-3 grid-cols-1 sm:grid-cols-2">
                {shops.map((shop) => {
                  const ShopIcon = getShopTypeIcon(shop.shopType);
                  return (
                    <Card
                      key={shop.id}
                      className="overflow-hidden transition-shadow hover:shadow-md"
                    >
                      <div
                        className={`relative flex h-28 items-center justify-center bg-gradient-to-br ${getShopTypeGradient(shop.shopType)}`}
                      >
                        <ShopIcon className="h-12 w-12 text-white/30" />
                        <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 Now' : 'এখন খালি')
                            : (language === 'en' ? 'Rented' : 'ভাড়া হয়েছে')}
                        </Badge>
                        <Badge className="absolute right-3 top-3 bg-white/90 text-[10px] text-gray-800 backdrop-blur-sm dark:bg-black/60 dark:text-gray-100">
                          {getShopTypeLabel(shop.shopType)}
                        </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-1 flex items-center gap-2 text-[10px] text-muted-foreground">
                          <span className="flex items-center gap-0.5">
                            <Maximize className="h-3 w-3" />
                            {shop.area ? `${shop.area} sqft` : '-'}
                          </span>
                        </div>
                        <div className="mt-3 flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            className="flex-1 text-[11px]"
                            onClick={() =>
                              handleToggleShopAvailable(shop.id, shop.isAvailable)
                            }
                          >
                            {shop.isAvailable ? (
                              <>
                                <EyeOff className="mr-1 h-3 w-3" />
                                {language === 'en' ? 'Mark as Rented' : 'ভাড়া হয়েছে চিহ্নিত'}
                              </>
                            ) : (
                              <>
                                <Eye className="mr-1 h-3 w-3" />
                                {language === 'en' ? 'Available Now' : 'এখন খালি'}
                              </>
                            )}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            className="text-[11px]"
                            onClick={() => {
                              setEditingShop(shop);
                              setShopFormOpen(true);
                            }}
                          >
                            <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={() => handleDeleteShop(shop.id)}
                                >
                                  {t('common.delete', language)}
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </div>

      {/* ─── Upload Choice Dialog ──────────────────────────────── */}
      <Dialog open={uploadChoiceOpen} onOpenChange={setUploadChoiceOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader className="flex-row items-center gap-2 space-y-0">
            <Button variant="ghost" size="sm" onClick={() => setUploadChoiceOpen(false)} 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 -ml-2">
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
            </Button>
            <DialogTitle>
              {language === 'en' ? 'What do you want to upload?' : 'আপনি কী আপলোড করতে চান?'}
            </DialogTitle>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-4 pt-2">
            <button
              onClick={() => {
                setUploadChoiceOpen(false);
                setEditingHouse(null);
                setHouseFormOpen(true);
              }}
              className="group flex flex-col items-center gap-3 rounded-xl border-2 border-primary/20 bg-primary/5 p-6 transition-all hover:border-primary hover:bg-primary/10 hover:shadow-md"
            >
              <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-primary/80 text-primary-foreground shadow-lg transition-transform group-hover:scale-110">
                <Home className="h-8 w-8" />
              </div>
              <div className="text-center">
                <p className="text-sm font-bold">
                  {language === 'en' ? 'House' : 'বাড়ি'}
                </p>
                <p className="text-[10px] text-muted-foreground">
                  {language === 'en'
                    ? 'Flat, House, Room, Mess'
                    : 'ফ্ল্যাট, বাড়ি, রুম, মেস'}
                </p>
              </div>
            </button>
            <button
              onClick={() => {
                setUploadChoiceOpen(false);
                setEditingShop(null);
                setShopFormOpen(true);
              }}
              className="group flex flex-col items-center gap-3 rounded-xl border-2 border-emerald-500/20 bg-emerald-500/5 p-6 transition-all hover:border-emerald-500 hover:bg-emerald-500/10 hover:shadow-md"
            >
              <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-600/80 text-white shadow-lg transition-transform group-hover:scale-110">
                <Store className="h-8 w-8" />
              </div>
              <div className="text-center">
                <p className="text-sm font-bold">
                  {language === 'en' ? 'Shop' : 'দোকান'}
                </p>
                <p className="text-[10px] text-muted-foreground">
                  {language === 'en'
                    ? 'Commercial, Office, Warehouse'
                    : 'কমার্শিয়াল, অফিস, গোডাউন'}
                </p>
              </div>
            </button>
          </div>
        </DialogContent>
      </Dialog>

      {/* ─── House Upload Dialog ───────────────────────────────── */}
      <Dialog open={houseFormOpen} onOpenChange={setHouseFormOpen}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          <DialogHeader className="flex-row items-center gap-2 space-y-0">
            <Button variant="ghost" size="sm" onClick={() => setHouseFormOpen(false)} 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 -ml-2">
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
            </Button>
            <DialogTitle>
              {editingHouse ? t('house.editHouse', language) : t('house.uploadHouse', language)}
            </DialogTitle>
          </DialogHeader>
          <HouseUploadForm
            language={language}
            ownerId={user.id}
            onSaved={() => {
              fetchMyHouses();
              setHouseFormOpen(false);
            }}
            editHouse={editingHouse}
            onCancelEdit={() => {
              setEditingHouse(null);
              setHouseFormOpen(false);
            }}
          />
        </DialogContent>
      </Dialog>

      {/* ─── Shop Upload Dialog ────────────────────────────────── */}
      <Dialog open={shopFormOpen} onOpenChange={setShopFormOpen}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-lg custom-scrollbar">
          <DialogHeader className="flex-row items-center gap-2 space-y-0">
            <Button variant="ghost" size="sm" onClick={() => setShopFormOpen(false)} 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 -ml-2">
              <ArrowLeft className="h-4 w-4" />
              <span>{language === 'en' ? 'Back' : 'ফিরুন'}</span>
            </Button>
            <DialogTitle>
              {editingShop
                ? (language === 'en' ? 'Edit Shop' : 'দোকান সম্পাদনা')
                : (language === 'en' ? 'Upload Shop' : 'দোকান আপলোড')}
            </DialogTitle>
          </DialogHeader>
          <ShopUploadForm
            language={language}
            ownerId={user.id}
            onSaved={() => {
              fetchMyShops();
              setShopFormOpen(false);
            }}
            editShop={editingShop}
            onCancelEdit={() => {
              setEditingShop(null);
              setShopFormOpen(false);
            }}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
}
