'use client';

import { useState, useEffect, useCallback } from 'react';
import { Search, Building2, Store, ShoppingBag, Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

const typeLabels: Record<string, string> = { houses: 'Houses', shops: 'Shops', products: 'Products' };
const typeIcons: Record<string, React.ElementType> = { houses: Building2, shops: Store, products: ShoppingBag };

export function AdminListings({ type }: { type: 'houses' | 'shops' | 'products' }) {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const TypeIcon = typeIcons[type];

  const fetchItems = useCallback(async () => {
    try { const r = await fetch(`/api/admin/listings?type=${type}`); const d = await r.json(); if (d.success) setItems(d.items); } catch { }
    finally { setLoading(false); }
  }, [type]);
  useEffect(() => { fetchItems(); }, [fetchItems]);

  const toggleAvail = async (id: string, cur: boolean) => {
    try { const r = await fetch('/api/admin/listings', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, type, isAvailable: !cur }) }); const d = await r.json(); if (d.success) fetchItems(); } catch { }
  };
  const deleteItem = async (id: string) => {
    try { const r = await fetch('/api/admin/listings', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, type }) }); const d = await r.json(); if (d.success) fetchItems(); } catch { }
  };

  const filtered = items.filter((item) => item.title?.toLowerCase().includes(searchQuery.toLowerCase()));
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        <Input placeholder={`Search ${typeLabels[type].toLowerCase()}...`} value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9" />
      </div>
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        {filtered.map((item) => (
          <Card key={item.id} className="group overflow-hidden border-0 shadow-sm transition-all hover:shadow-md">
            <div className="relative h-32 bg-gradient-to-br from-slate-100 to-slate-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center">
              <TypeIcon className="h-10 w-10 text-slate-300 dark:text-slate-600" strokeWidth={1.5} />
              <Badge className={`absolute right-3 top-3 text-[10px] border-0 ${item.isAvailable ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>{item.isAvailable ? 'Active' : 'Inactive'}</Badge>
            </div>
            <CardContent className="p-4">
              <h3 className="truncate text-sm font-semibold">{item.title}</h3>
              <p className="mt-1 text-xs text-muted-foreground line-clamp-2">{item.description?.slice(0, 80)}...</p>
              <div className="mt-2 flex items-center justify-between">
                <span className="text-sm font-bold text-orange-600 dark:text-orange-400">৳{item.price?.toLocaleString()}{type !== 'products' ? '/mo' : ''}</span>
                {item.owner && <span className="text-[10px] text-muted-foreground">by {item.owner.name}</span>}
                {item.seller && <span className="text-[10px] text-muted-foreground">by {item.seller.name}</span>}
              </div>
              <div className="mt-3 flex items-center gap-2">
                <Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => toggleAvail(item.id, item.isAvailable)}>{item.isAvailable ? 'Suspend' : 'Activate'}</Button>
                <AlertDialog>
                  <AlertDialogTrigger asChild><Button variant="outline" size="sm" className="text-xs text-destructive hover:bg-destructive/5"><Trash2 className="h-3.5 w-3.5" /></Button></AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader><AlertDialogTitle>Delete {typeLabels[type].slice(0, -1)}</AlertDialogTitle><AlertDialogDescription>Delete &quot;{item.title}&quot; permanently?</AlertDialogDescription></AlertDialogHeader>
                    <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => deleteItem(item.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Delete</AlertDialogAction></AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </CardContent>
          </Card>
        ))}
        {filtered.length === 0 && (
          <div className="col-span-full py-16 text-center">
            <TypeIcon className="mx-auto h-12 w-12 text-slate-300 dark:text-slate-600" strokeWidth={1.5} />
            <p className="mt-3 text-sm text-muted-foreground">No {typeLabels[type].toLowerCase()} found</p>
          </div>
        )}
      </div>
    </div>
  );
}
