"use client";

import { type ServiceStatus } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

interface ServicesTabProps {
  isSuperAdmin: boolean;
  services: ServiceStatus[];
  servicesLoading: boolean;
  serviceActionLoading: string | null;
  serviceError: string;
  onLoadServices: () => void;
  onServiceAction: (name: string, action: "start" | "stop" | "restart" | "enable" | "disable" | "block_external" | "allow_external") => void;
}

export function ServicesTab({
  isSuperAdmin,
  services,
  servicesLoading,
  serviceActionLoading,
  serviceError,
  onLoadServices,
  onServiceAction,
}: ServicesTabProps) {
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Systemdienste</h2>
        <Button variant="outline" size="sm" onClick={onLoadServices} disabled={servicesLoading}>
          {servicesLoading ? "..." : "Aktualisieren"}
        </Button>
      </div>

      {serviceError && (
        <Alert variant="destructive">
          <AlertDescription>{serviceError}</AlertDescription>
        </Alert>
      )}

      {servicesLoading && services.length === 0 ? (
        <Card>
          <CardContent className="p-4 space-y-3">
            {Array.from({ length: 5 }).map((_, i) => (
              <Skeleton key={i} className="h-12 w-full" />
            ))}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-44">Dienst</TableHead>
                <TableHead className="w-28">Status</TableHead>
                <TableHead className="w-24">Autostart</TableHead>
                <TableHead className="w-28">Externer Zugriff</TableHead>
                <TableHead>Beschreibung</TableHead>
                {isSuperAdmin && <TableHead className="w-72 text-right">Aktionen</TableHead>}
              </TableRow>
            </TableHeader>
            <TableBody>
              {services.map((svc) => {
                const isActive = svc.active === "active";
                const isFailed = svc.active === "failed";
                const isEnabled = svc.enabled === "enabled" || svc.enabled === "static";
                const busy = (key: string) => serviceActionLoading === `${svc.name}:${key}`;
                const anyBusy = serviceActionLoading?.startsWith(`${svc.name}:`) ?? false;
                return (
                  <TableRow key={svc.name}>
                    <TableCell className="font-mono text-sm font-medium">
                      {svc.name}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={isActive ? "default" : isFailed ? "destructive" : "secondary"}
                      >
                        {svc.active === "active"
                          ? `Aktiv (${svc.sub})`
                          : svc.active === "failed"
                          ? "Fehler"
                          : svc.active === "inactive"
                          ? "Gestoppt"
                          : svc.active}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={isEnabled ? "default" : "outline"}>
                        {svc.enabled === "enabled"
                          ? "Aktiviert"
                          : svc.enabled === "disabled"
                          ? "Deaktiviert"
                          : svc.enabled === "static"
                          ? "Statisch"
                          : svc.enabled}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {svc.external_blocked !== undefined ? (
                        <Badge variant={svc.external_blocked ? "destructive" : "default"}>
                          {svc.external_blocked ? "Gesperrt" : "Offen"}
                        </Badge>
                      ) : (
                        <span className="text-xs text-muted-foreground">–</span>
                      )}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground truncate max-w-xs">
                      {svc.description || "–"}
                    </TableCell>
                    {isSuperAdmin && (
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-1 flex-wrap">
                        {isActive ? (
                          <>
                            <Button
                              size="sm"
                              variant="outline"
                              disabled={anyBusy}
                              onClick={() => onServiceAction(svc.name, "restart")}
                            >
                              {busy("restart") ? "..." : "Neustart"}
                            </Button>
                            <Button
                              size="sm"
                              variant="destructive"
                              disabled={anyBusy}
                              onClick={() => onServiceAction(svc.name, "stop")}
                            >
                              {busy("stop") ? "..." : "Stop"}
                            </Button>
                          </>
                        ) : (
                          <Button
                            size="sm"
                            variant="default"
                            disabled={anyBusy}
                            onClick={() => onServiceAction(svc.name, "start")}
                          >
                            {busy("start") ? "..." : "Start"}
                          </Button>
                        )}
                        {svc.enabled === "enabled" ? (
                          <Button
                            size="sm"
                            variant="outline"
                            disabled={anyBusy}
                            onClick={() => onServiceAction(svc.name, "disable")}
                          >
                            {busy("disable") ? "..." : "Deaktivieren"}
                          </Button>
                        ) : svc.enabled === "disabled" ? (
                          <Button
                            size="sm"
                            variant="outline"
                            disabled={anyBusy}
                            onClick={() => onServiceAction(svc.name, "enable")}
                          >
                            {busy("enable") ? "..." : "Aktivieren"}
                          </Button>
                        ) : null}
                        {svc.external_blocked !== undefined && (
                          svc.external_blocked ? (
                            <Button
                              size="sm"
                              variant="outline"
                              disabled={anyBusy}
                              onClick={() => onServiceAction(svc.name, "allow_external")}
                            >
                              {busy("allow_external") ? "..." : "Extern freigeben"}
                            </Button>
                          ) : (
                            <Button
                              size="sm"
                              variant="outline"
                              disabled={anyBusy}
                              onClick={() => onServiceAction(svc.name, "block_external")}
                            >
                              {busy("block_external") ? "..." : "Extern sperren"}
                            </Button>
                          )
                        )}
                      </div>
                    </TableCell>
                    )}
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </Card>
      )}
    </div>
  );
}
