'use client';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import type { PolicySettingSearchResult } from '@/lib/actions/policySettings';
import { PolicyTypeBadge } from './PolicyTypeBadge';
import { formatDistanceToNow } from 'date-fns';
import { de } from 'date-fns/locale';

interface PolicyTableProps {
  policies: PolicySettingSearchResult[];
  onRowClick: (policy: PolicySettingSearchResult) => void;
}

export function PolicyTable({ policies, onRowClick }: PolicyTableProps) {
  if (policies.length === 0) {
    return null;
  }

  return (
    <Card>
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Setting Name</TableHead>
                <TableHead>Setting Value</TableHead>
                <TableHead>Policy Name</TableHead>
                <TableHead>Policy Type</TableHead>
                <TableHead>Last Synced</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {policies.map((policy) => (
                <TableRow
                  key={policy.id}
                  onClick={() => onRowClick(policy)}
                  className="cursor-pointer hover:bg-accent"
                >
                  <TableCell className="font-medium">
                    {policy.settingName}
                  </TableCell>
                  <TableCell className="max-w-xs truncate">
                    {policy.settingValue}
                  </TableCell>
                  <TableCell>{policy.policyName}</TableCell>
                  <TableCell>
                    <PolicyTypeBadge type={policy.policyType} />
                  </TableCell>
                  <TableCell className="text-muted-foreground text-sm">
                    {formatDistanceToNow(new Date(policy.lastSyncedAt), {
                      addSuffix: true,
                      locale: de,
                    })}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
