
"use client";

import { useState, useMemo, useTransition } from 'react';
import type { TariFile } from '@/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Trash2, Search, Copy, Loader2, ExternalLink } from 'lucide-react';
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle, 
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import { deleteGeneralTariImage } from '@/lib/actions';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { TARI_GENERAL_IMAGES_FOLDER } from '@/constants';

interface ImageListClientProps {
  initialImages: TariFile[];
  fetchError?: string;
}

export function ImageListClient({ initialImages, fetchError }: ImageListClientProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const { toast } = useToast();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const [imageToDelete, setImageToDelete] = useState<TariFile | null>(null);
  const [isDeleteAlertOpen, setIsDeleteAlertOpen] = useState(false);

  const filteredImages = useMemo(() => {
    if (!searchTerm) {
      return initialImages;
    }
    const lowercasedFilter = searchTerm.toLowerCase();
    return initialImages.filter((image) => 
      image.name?.toLowerCase().includes(lowercasedFilter) ||
      image.path?.toLowerCase().includes(lowercasedFilter)
    );
  }, [searchTerm, initialImages]);

  const handleDeleteClick = (image: TariFile) => {
    setImageToDelete(image);
    setIsDeleteAlertOpen(true);
  };

  const confirmDelete = async () => {
    if (!imageToDelete || !imageToDelete.path) return;

    startTransition(async () => {
      const result = await deleteGeneralTariImage(imageToDelete.path);
      if (result.success) {
        toast({ title: "Success", description: result.message });
        router.refresh(); 
      } else {
        toast({ title: "Error", description: result.message, variant: "destructive" });
      }
      setImageToDelete(null);
      setIsDeleteAlertOpen(false);
    });
  };

  const handleCopyUrl = (url: string) => {
    navigator.clipboard.writeText(url)
      .then(() => toast({ title: "Copied!", description: "Image URL copied to clipboard." }))
      .catch(() => toast({ title: "Error", description: "Failed to copy URL.", variant: "destructive" }));
  };

  if (fetchError) {
    return (
      <Card className="shadow-lg">
        <CardHeader>
          <CardTitle>Error Fetching Images</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-destructive">{fetchError}</p>
          <p className="text-muted-foreground mt-2">Please check server logs and ensure Tari API credentials and permissions are correct.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card className="shadow-lg mt-6">
        <CardHeader>
          <CardTitle>Stored Images</CardTitle>
          <CardDescription>
            Displaying {filteredImages.length} of {initialImages.length} image(s) from Tari folder: &quot;{TARI_GENERAL_IMAGES_FOLDER}&quot;.
          </CardDescription>
          <div className="relative mt-4">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
            <Input
              type="text"
              placeholder="Search images by name or path..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 w-full sm:w-1/2 lg:w-1/3"
              aria-label="Search images"
            />
          </div>
        </CardHeader>
        <CardContent>
          {initialImages.length === 0 ? (
            <div className="py-10 text-center text-muted-foreground">
              <p className="mb-2 text-lg font-semibold">No images found in this folder.</p>
              <p className="text-sm">
                Upload new images using the button above.
              </p>
            </div>
          ) : filteredImages.length === 0 && searchTerm ? (
            <div className="py-10 text-center text-muted-foreground">
              <p className="mb-2 text-lg font-semibold">No images match your search &quot;{searchTerm}&quot;.</p>
              <p className="text-sm">
                Try a different search term or clear the search.
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
              {filteredImages.map((image) => {
                const displayUrl = image.public_url || image.url;
                return (
                  <Card key={image.path} className="group overflow-hidden flex flex-col">
                    <div className="relative w-full aspect-square bg-muted">
                      <Image
                        src={displayUrl} 
                        alt={image.name}
                        fill
                        style={{ objectFit: 'contain' }} 
                        sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 20vw"
                        onError={(e) => { e.currentTarget.src = `https://placehold.co/200x200.png?text=Error`; }}
                      />
                    </div>
                    <CardContent className="p-3 text-xs flex-grow flex flex-col justify-between">
                      <div>
                        <p className="font-medium truncate" title={image.name}>{image.name}</p>
                        <p className="text-muted-foreground truncate" title={image.path}>Path: {image.path}</p>
                        {image.size && <p className="text-muted-foreground">Size: {(image.size / 1024).toFixed(1)} KB</p>}
                      </div>
                      <div className="mt-2 flex flex-col sm:flex-row gap-1.5 items-center justify-end">
                         <Button 
                          variant="outline" 
                          size="icon" 
                          className="h-7 w-7"
                          onClick={() => handleCopyUrl(displayUrl)}
                          title="Copy URL"
                        >
                          <Copy className="h-3.5 w-3.5" />
                        </Button>
                         <Button 
                          variant="outline" 
                          size="icon" 
                          className="h-7 w-7"
                          asChild
                          title="Open Image in New Tab"
                        >
                          <a href={displayUrl} target="_blank" rel="noopener noreferrer">
                              <ExternalLink className="h-3.5 w-3.5" />
                          </a>
                        </Button>
                        <Button 
                          variant="destructive" 
                          size="icon" 
                          className="h-7 w-7"
                          onClick={() => handleDeleteClick(image)}
                          disabled={isPending && imageToDelete?.path === image.path}
                          title="Delete Image"
                        >
                          {isPending && imageToDelete?.path === image.path ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      <AlertDialog open={isDeleteAlertOpen} onOpenChange={setIsDeleteAlertOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This will permanently delete the image &quot;{imageToDelete?.name}&quot; from Tari. This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setImageToDelete(null)} disabled={isPending}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} disabled={isPending} className="bg-destructive hover:bg-destructive/90">
              {isPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
