'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { useFeedback } from '../../hooks/useFeedback';

const columns = [
  'ID',
  'Created By',
  'Social Network',
  'Rating',
  'Username',
  'Comment',
  'Attachment',
  'Created At',
];

const ratingVariant = (
  rating: string,
): 'success' | 'warning' | 'destructive' => {
  if (rating === "Yes, it's great!") return 'success';
  if (rating === 'Could be better!') return 'warning';
  return 'destructive';
};

const formatDate = (dateString: string) =>
  new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });

export function FeedbackList() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const page = Number(searchParams?.get('page') || 1);
  const { data, isLoading } = useFeedback(page);

  const handlePageChange = (p: number) => {
    const params = new URLSearchParams(searchParams?.toString());
    params.set('page', String(p));
    router.push(`?${params.toString()}`);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Feedback</CardTitle>
      </CardHeader>

      <CardContent className="overflow-x-auto p-0">
        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Spinner className="size-6 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <Table className="min-w-max">
            <TableHeader>
              <TableRow className="bg-accent/60">
                {columns.map((col) => (
                  <TableHead
                    key={col}
                    className="min-w-[120px] h-10 whitespace-nowrap"
                  >
                    {col}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {(data?.items ?? []).length > 0 ? (
                data!.items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell className="whitespace-nowrap">{item.id}</TableCell>
                    <TableCell className="whitespace-nowrap">
                      {item.created_by?.user_name || '-'}
                    </TableCell>
                    <TableCell className="whitespace-nowrap capitalize">
                      {item.social_network}
                    </TableCell>
                    <TableCell className="whitespace-nowrap">
                      <Badge
                        variant={ratingVariant(item.rating)}
                        appearance="outline"
                      >
                        {item.rating}
                      </Badge>
                    </TableCell>
                    <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                      {item.username}
                    </TableCell>
                    <TableCell className="whitespace-nowrap text-sm">
                      {item.comment || '-'}
                    </TableCell>
                    <TableCell className="whitespace-nowrap">
                      {item.attachment ? (
                        <a
                          href={item.attachment}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-primary underline text-sm"
                          onClick={(e) => e.stopPropagation()}
                        >
                          View
                        </a>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell className="whitespace-nowrap text-sm">
                      {formatDate(item.created_at)}
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell
                    colSpan={columns.length}
                    className="text-center py-8 text-muted-foreground"
                  >
                    No feedback found
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </CardContent>

      {(data?.total_pages ?? 0) > 1 && (
        <CardFooter className="justify-center">
          <PaginationComponent
            currentPage={page}
            totalPages={data?.total_pages ?? 1}
            onPageChange={handlePageChange}
          />
        </CardFooter>
      )}
    </Card>
  );
}
