'use client';

import Link from 'next/link';
import { format } from 'date-fns';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Eye, FileText, Trash2 } from 'lucide-react';
import type { Document } from '@/firebase/firestore/data';
import { useFirebase } from '@/firebase';
import { deleteDocumentAndSubcollections } from '@/firebase/firestore/data';
import { useRouter } from 'next/navigation';
import { useToast } from '@/hooks/use-toast';

function DeleteButton({ id }: { id: string }) {
  const { firestore, user } = useFirebase();
  const router = useRouter();
  const { toast } = useToast();

  const handleDelete = async () => {
    if (firestore && user) {
      try {
        await deleteDocumentAndSubcollections(firestore, user.uid, id);
        toast({
          title: 'Document deleted',
          description: 'The document has been successfully deleted.',
        });
        router.refresh();
      } catch (error) {
        console.error('Failed to delete document:', error);
        toast({
          title: 'Error',
          description: 'Failed to delete the document.',
          variant: 'destructive',
        });
      }
    }
  };

  return (
    <Button variant="ghost" size="icon" onClick={handleDelete}>
      <Trash2 className="h-4 w-4" />
      <span className="sr-only">Delete</span>
    </Button>
  );
}

export function DocumentTable({ documents }: { documents: Document[] }) {
  if (documents.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>No Documents Yet</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex flex-col items-center justify-center text-center p-8 border-2 border-dashed rounded-lg">
            <FileText className="w-12 h-12 mb-4 text-muted-foreground" />
            <p className="text-muted-foreground">Upload your first document to see it here.</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Recent Summaries</CardTitle>
      </CardHeader>
      <CardContent>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead className="hidden sm:table-cell">Created At</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {documents.map((doc) => (
              <TableRow key={doc.id}>
                <TableCell className="font-medium">{doc.name}</TableCell>
                <TableCell className="hidden sm:table-cell">
                  {format(new Date(doc.createdAt), 'PPP')}
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end items-center gap-2">
                    <Button asChild variant="ghost" size="icon">
                      <Link href={`/dashboard/summaries/${doc.id}`}>
                        <Eye className="h-4 w-4" />
                        <span className="sr-only">View</span>
                      </Link>
                    </Button>
                    <DeleteButton id={doc.id} />
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
