'use client';

import Guard from '@/components/guard';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useGroupSensors } from '@/hooks/useGroupSensor';
import Link from 'next/link';
import { useParams, useRouter } from 'next/navigation';

export default function GroupSensorsPage() {
  const params = useParams();
  const groupId = Number(params.groupId);
  const router = useRouter();
  const { data, isLoading, isError, refetch } = useGroupSensors(groupId);

  return (
    <Guard>
      <main className="mx-auto max-w-full px-4 py-6">
        <div className="mb-4 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Button variant="ghost" onClick={() => router.back()}>
              〈
            </Button>
            <h1 className="text-xl font-semibold">센서 그룹</h1>
          </div>
          <Button onClick={() => refetch()}>새로고침</Button>
        </div>

        {isLoading && <p className="text-gray-500">불러오는 중...</p>}
        {isError && <p className="text-red-600">불러오지 못했습니다.</p>}
        {!isLoading && !isError && (
          <div className="overflow-x-auto rounded border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="px-4 py-2 text-center">ID</TableHead>
                  <TableHead className="px-4 py-2 text-center">이름</TableHead>
                  <TableHead className="px-4 py-2 text-center">단위</TableHead>
                  <TableHead className="px-4 py-2 text-center">데이터</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data && data.length > 0 ? (
                  data.map((s) => (
                    <TableRow key={s.id}>
                      <TableCell className="px-4 py-2 text-center">{s.id}</TableCell>
                      <TableCell className="px-4 py-2 text-center">{s.name}</TableCell>
                      <TableCell className="px-4 py-2 text-center">{s.unit ?? '-'}</TableCell>
                      <TableCell className="flex items-center justify-center px-4 py-2 text-center">
                        <Button asChild variant="outline">
                          <Link href={`/sensors/${s.id}`}>센서보기</Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={4} className="px-4 py-6 text-center text-gray-500">
                      데이터가 없습니다.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        )}
      </main>
    </Guard>
  );
}
