
"use client";

import { useState, useEffect, useMemo, useTransition } from 'react';
import type { Project as ProjectType } from '@/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Edit, Trash2, Search, Loader2 } from 'lucide-react';
import { ProjectAdminImage } from './ProjectAdminImage';
import { 
  AlertDialog, 
  AlertDialogAction, 
  AlertDialogCancel, 
  AlertDialogContent, 
  AlertDialogDescription, 
  AlertDialogFooter, 
  AlertDialogHeader, 
  AlertDialogTitle, 
  AlertDialogTrigger 
} from '@/components/ui/alert-dialog';
import { useToast } from '@/hooks/use-toast';
import { deleteProject } from '@/lib/actions';
import { useRouter } from 'next/navigation';
import { EditProjectForm } from './EditProjectForm'; // Import the new EditProjectForm

interface ProjectListClientProps {
  initialProjects: ProjectType[];
}

export function ProjectListClient({ initialProjects }: ProjectListClientProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [projects, setProjects] = useState<ProjectType[]>(initialProjects);
  const { toast } = useToast();
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const [projectToDelete, setProjectToDelete] = useState<ProjectType | null>(null);
  const [isDeleteAlertOpen, setIsDeleteAlertOpen] = useState(false);

  const [projectToEdit, setProjectToEdit] = useState<ProjectType | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);


  useEffect(() => {
    setProjects(initialProjects);
  }, [initialProjects]);

  const filteredProjects = useMemo(() => {
    if (!searchTerm) {
      return projects;
    }
    const lowercasedFilter = searchTerm.toLowerCase();
    return projects.filter((project) => {
      return (
        project.title?.toLowerCase().includes(lowercasedFilter) ||
        project.organization?.toLowerCase().includes(lowercasedFilter) ||
        project.description?.toLowerCase().includes(lowercasedFilter)
      );
    });
  }, [searchTerm, projects]);

  const handleDeleteClick = (project: ProjectType) => {
    setProjectToDelete(project);
    setIsDeleteAlertOpen(true);
  };

  const confirmDelete = async () => {
    if (!projectToDelete) return;

    startTransition(async () => {
      const result = await deleteProject(projectToDelete.id);
      if (result.success) {
        toast({ title: "Success", description: result.message });
        // Optimistic update or rely on revalidatePath from server action
        // setProjects(prev => prev.filter(p => p.id !== projectToDelete.id));
        router.refresh(); // Re-fetches data due to revalidatePath in server action
      } else {
        toast({ title: "Error", description: result.message, variant: "destructive" });
      }
      setProjectToDelete(null);
      setIsDeleteAlertOpen(false);
    });
  };

  const handleEditClick = (project: ProjectType) => {
    setProjectToEdit(project);
    setIsEditModalOpen(true);
  };


  return (
    <>
      <Card className="shadow-lg">
        <CardHeader>
          <CardTitle>Existing Projects</CardTitle>
          <CardDescription>
            Displaying {filteredProjects.length} of {projects.length} project(s) from the database.
          </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 projects (title, organization, description)..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 w-full sm:w-1/2 lg:w-1/3"
              aria-label="Search projects"
            />
          </div>
        </CardHeader>
        <CardContent>
          {projects.length === 0 ? (
            <div className="py-10 text-center text-muted-foreground">
              <p className="mb-2 text-lg font-semibold">No projects found.</p>
              <p className="text-sm">
                This could be because no projects have been added yet, or there was an issue fetching data.
              </p>
              <p className="text-sm mt-2 font-medium text-destructive">
                Please <strong>check your server terminal logs</strong> for specific error messages from Firestore.
              </p>
              <p className="text-xs mt-1 text-destructive-foreground/80 bg-destructive/80 p-2 rounded-md inline-block">
                  Common errors include <code className="font-mono">permission-denied</code> (check Firestore Security Rules) or <code className="font-mono">failed-precondition</code> (check for missing Firestore Indexes if ordering is active).
                </p>
              <p className="text-sm mt-3">
                You can also try adding a new project to see if data interaction is working.
              </p>
            </div>
          ) : filteredProjects.length === 0 && searchTerm ? (
            <div className="py-10 text-center text-muted-foreground">
              <p className="mb-2 text-lg font-semibold">No projects match your search &quot;{searchTerm}&quot;.</p>
              <p className="text-sm">
                Try a different search term or clear the search to see all projects.
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[60px] sm:w-[80px]">Image</TableHead>
                    <TableHead>Title</TableHead>
                    <TableHead className="hidden md:table-cell">Organization</TableHead>
                    <TableHead className="hidden lg:table-cell">Created At</TableHead>
                    <TableHead className="text-right w-[120px] sm:w-[150px]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredProjects.map((project) => {
                    const imageSrc = (project.imageUrl && (project.imageUrl.startsWith('/') || project.imageUrl.startsWith('http')))
                                    ? project.imageUrl 
                                    : `https://placehold.co/80x80.png?text=${encodeURIComponent(project.title?.substring(0,3) || 'N/A')}`;
                    
                    let displayDate = 'N/A';
                    if (project.createdAt && typeof project.createdAt === 'string') {
                      try {
                        displayDate = new Date(project.createdAt).toLocaleDateString();
                      } catch (e) {
                        // console.warn("Error parsing date string:", project.createdAt, e);
                      }
                    }
                    return (
                      <TableRow key={project.id}>
                        <TableCell>
                          <ProjectAdminImage 
                            src={imageSrc}
                            alt={project.title || 'Project Image'}
                            imageHint={project.imageHint}
                          />
                        </TableCell>
                        <TableCell className="font-medium">{project.title || 'N/A'}</TableCell>
                        <TableCell className="hidden md:table-cell">{project.organization || 'N/A'}</TableCell>
                        <TableCell className="hidden lg:table-cell text-xs">{displayDate}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button 
                              variant="outline" 
                              size="icon" 
                              onClick={() => handleEditClick(project)}
                              disabled={isPending}
                              aria-label={`Edit project ${project.title || 'N/A'}`}
                              title="Edit Project">
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button 
                              variant="destructive" 
                              size="icon" 
                              onClick={() => handleDeleteClick(project)}
                              disabled={isPending}
                              aria-label={`Delete project ${project.title || 'N/A'}`}
                              title="Delete Project">
                              {isPending && projectToDelete?.id === project.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={isDeleteAlertOpen} onOpenChange={setIsDeleteAlertOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the project
              &quot;{projectToDelete?.title}&quot; and its associated image file from the server.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setProjectToDelete(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>

      {/* Edit Project Modal */}
      {projectToEdit && (
        <EditProjectForm
          project={projectToEdit}
          isOpen={isEditModalOpen}
          onOpenChange={(open) => {
            setIsEditModalOpen(open);
            if (!open) {
              setProjectToEdit(null); // Clear projectToEdit when modal closes
            }
          }}
        />
      )}
    </>
  );
}
