'use client';

import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useSensorGroups } from '@/hooks/useSensorGroups';
import Link from 'next/link';

export default function SensorGroupPage() {
  const { data, isLoading, isError, refetch } = useSensorGroups();

  return (
    <main className="mx-auto px-4 py-6">
      <div className="mb-4 flex items-center justify-between">
        <h1 className="text-xl font-semibold">센서 그룹</h1>
        <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((g) => (
                  <TableRow key={g.id}>
                    <TableCell className="px-4 py-2 text-center">{g.id}</TableCell>
                    <TableCell className="px-4 py-2 text-center">{g.name}</TableCell>
                    <TableCell className="px-4 py-2 text-center">{g.description ?? '-'}</TableCell>
                    <TableCell className="flex items-center justify-center px-4 py-2">
                      <Button asChild variant="outline">
                        <Link href={`/sensor-groups/${g.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>
  );
}
