import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import {
  BookOpenText,
  Plus,
  Search,
  ServerCog,
  ShieldHalf,
} from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "../../components/ui/avatar";
import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../components/ui/card";
import { CopyButton } from "../../components/ui/copy-button";
import { Input } from "../../components/ui/input";
import { Separator } from "../../components/ui/separator";
import { Switch } from "../../components/ui/switch";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../components/ui/table";
import { toast } from "../../components/ui/use-toast";
import {
  deleteClient,
  fetchClients,
  updateClientStatus,
} from "../../lib/devApi";
import { t } from "../../lib/i18n";
import { cn } from "../../lib/utils";

function ClientsPage() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { data, isLoading, error } = useQuery({
    queryKey: ["clients"],
    queryFn: fetchClients,
  });
  const updateStatusMutation = useMutation({
    mutationFn: (payload: { id: string; status: "active" | "inactive" }) =>
      updateClientStatus(payload.id, payload.status),
    onSuccess: (_, variables) => {
      const statusText =
        variables.status === "active"
          ? t("ui.common.status.active", "활성화")
          : t("ui.common.status.inactive", "비활성화");
      toast(
        t(
          "msg.dev.clients.status_updated",
          "클라이언트가 {{status}}되었습니다.",
          {
            status: statusText,
          },
        ),
      );
      queryClient.invalidateQueries({ queryKey: ["clients"] });
    },
    onError: (error: AxiosError<{ error?: string }>) => {
      const errMsg =
        error.response?.data?.error ??
        error.message ??
        t(
          "msg.dev.clients.status_update_error",
          "Failed to update client status",
        );
      toast(errMsg, "error");
    },
  });
  const deleteMutation = useMutation({
    mutationFn: (clientId: string) => deleteClient(clientId),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["clients"] }),
  });

  const clients = data?.items || [];
  const totalClients = clients.length;
  // TODO: Add real stats for active sessions and auth failures
  type StatTone = "up" | "down" | "stable";
  type StatItem = {
    labelKey: string;
    labelFallback: string;
    value: string;
    deltaKey: string;
    deltaFallback: string;
    tone: StatTone;
  };

  const stats: StatItem[] = [
    {
      labelKey: "ui.dev.clients.stats.total",
      labelFallback: "총 클라이언트",
      value: totalClients.toString(),
      deltaKey: "ui.dev.clients.stats.realtime",
      deltaFallback: "Realtime",
      tone: "up" as const,
    },
    {
      labelKey: "ui.dev.clients.stats.active_sessions",
      labelFallback: "활성 세션",
      value: "-",
      deltaKey: "ui.dev.clients.stats.not_impl",
      deltaFallback: "Not impl",
      tone: "stable" as const,
    },
    {
      labelKey: "ui.dev.clients.stats.auth_failures",
      labelFallback: "인증 실패 (24h)",
      value: "0",
      deltaKey: "ui.dev.clients.stats.stable",
      deltaFallback: "Stable",
      tone: "stable" as const,
    },
  ];

  if (isLoading) {
    return (
      <div className="p-8 text-center">
        {t("msg.dev.clients.loading", "Loading clients...")}
      </div>
    );
  }

  if (error) {
    const errMsg =
      (error as AxiosError<{ error?: string }>).response?.data?.error ??
      (error as Error).message;
    return (
      <div className="p-8 text-center text-red-500">
        {t("msg.dev.clients.load_error", "Error loading clients: {{error}}", {
          error: errMsg,
        })}
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <Card className="glass-panel">
        <CardHeader className="pb-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                {t("ui.dev.clients.registry.title", "RP registry")}
              </p>
              <CardTitle className="text-3xl font-black tracking-tight">
                {t("ui.dev.clients.registry.subtitle", "Relying Parties")}
              </CardTitle>
              <CardDescription>
                {t(
                  "msg.dev.clients.registry.description",
                  "OIDC 클라이언트, 인증 방식, 리다이렉트 URI, 비밀키 재발행을 감사 로그와 함께 관리합니다.",
                )}
              </CardDescription>
            </div>
            <div className="hidden items-center gap-2 md:flex">
              <Button
                size="sm"
                className="shadow-lg shadow-primary/30"
                onClick={() => navigate("/clients/new")}
              >
                <Plus className="h-4 w-4" />
                {t("ui.dev.clients.new", "새 클라이언트")}
              </Button>
            </div>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-[1.5fr,1fr]">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                className="pl-10"
                placeholder={t(
                  "ui.dev.clients.search_placeholder",
                  "클라이언트 이름/ID로 검색...",
                )}
              />
            </div>
            <div className="flex items-center justify-end gap-2 md:justify-start">
              <Badge variant="muted">
                {t("ui.dev.clients.badge.tenant_selected", "테넌트: 선택됨")}
              </Badge>
              <Badge variant="success">
                {t("ui.dev.clients.badge.admin_session", "관리자 세션")}
              </Badge>
            </div>
          </div>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="grid gap-4 md:grid-cols-3">
            {stats.map((item) => (
              <Card key={item.labelKey} className="border border-border/60">
                <CardHeader className="pb-2">
                  <CardDescription>
                    {t(item.labelKey, item.labelFallback)}
                  </CardDescription>
                  <div className="mt-1 flex items-baseline gap-2">
                    <span className="text-3xl font-bold">{item.value}</span>
                    <Badge
                      variant={item.tone === "up" ? "success" : "muted"}
                      className={cn(
                        "px-2",
                        item.tone === "stable" && "bg-muted/40 text-foreground",
                      )}
                    >
                      {t(item.deltaKey, item.deltaFallback)}
                    </Badge>
                  </div>
                </CardHeader>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card className="glass-panel">
        <CardHeader className="pb-0">
          <div className="flex items-center justify-between">
            <CardTitle className="text-xl font-semibold">
              {t("ui.dev.clients.list.title", "클라이언트 목록")}
            </CardTitle>
            <div className="flex items-center gap-2 md:hidden">
              <Button size="sm" onClick={() => navigate("/clients/new")}>
                <Plus className="h-4 w-4" />
                {t("ui.dev.clients.new", "새 클라이언트")}
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>
                  {t("ui.dev.clients.table.application", "애플리케이션")}
                </TableHead>
                <TableHead>
                  {t("ui.dev.clients.table.client_id", "Client ID")}
                </TableHead>
                <TableHead>{t("ui.dev.clients.table.type", "유형")}</TableHead>
                <TableHead>
                  {t("ui.dev.clients.table.status", "상태")}
                </TableHead>
                <TableHead>
                  {t("ui.dev.clients.table.created_at", "생성일")}
                </TableHead>
                <TableHead className="text-right">
                  {t("ui.dev.clients.table.actions", "액션")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {clients.map((client) => (
                <TableRow key={client.id} className="bg-card/40">
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
                        {client.type === "confidential" ? (
                          <ServerCog className="h-4 w-4" />
                        ) : (
                          <ShieldHalf className="h-4 w-4" />
                        )}
                      </div>
                      <div>
                        <p className="font-semibold">
                          {client.name ||
                            t("ui.dev.clients.untitled", "Untitled")}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {t("ui.dev.clients.tenant_scoped", "Tenant-scoped")}
                        </p>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <code className="rounded-md bg-secondary/60 px-2 py-1 font-mono text-xs text-muted-foreground">
                        {client.id}
                      </code>
                      <CopyButton
                        value={client.id}
                        variant="ghost"
                        className="h-8 w-8 text-muted-foreground hover:text-primary"
                        aria-label={t(
                          "ui.dev.clients.copy_client_id",
                          "Copy client id",
                        )}
                        onCopy={() =>
                          toast(
                            t(
                              "msg.dev.clients.copy_client_id",
                              "클라이언트 ID가 복사되었습니다.",
                            ),
                          )
                        }
                      />
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        client.type === "confidential" ? "success" : "muted"
                      }
                    >
                      {client.type === "confidential"
                        ? t(
                            "ui.dev.clients.type.confidential",
                            "기밀(Confidential)",
                          )
                        : t("ui.dev.clients.type.public", "Public")}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <Switch
                        disabled={
                          updateStatusMutation.isPending &&
                          updateStatusMutation.variables?.id === client.id
                        }
                        checked={client.status === "active"}
                        onCheckedChange={(checked) =>
                          updateStatusMutation.mutate({
                            id: client.id,
                            status: checked ? "active" : "inactive",
                          })
                        }
                      />
                      <span
                        className={cn(
                          "text-sm font-medium",
                          client.status === "active"
                            ? "text-emerald-400"
                            : "text-muted-foreground",
                        )}
                      >
                        {client.status === "active"
                          ? t("ui.common.status.active", "활성")
                          : t("ui.common.status.inactive", "비활성")}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="text-muted-foreground">
                    {client.createdAt
                      ? new Date(client.createdAt).toLocaleDateString()
                      : "-"}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button variant="ghost" size="sm" asChild>
                        <Link to={`/clients/${client.id}`}>
                          {t("ui.common.edit", "Edit")}
                        </Link>
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-muted-foreground hover:text-destructive"
                        onClick={() => deleteMutation.mutate(client.id)}
                      >
                        {t("ui.common.delete", "Delete")}
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          <div className="mt-4 flex items-center justify-between rounded-xl border border-border/60 bg-secondary/60 px-4 py-3 text-sm text-muted-foreground">
            <span>
              {t(
                "msg.dev.clients.showing",
                "Showing {{shown}} of {{total}} clients",
                { shown: clients.length, total: totalClients },
              )}
            </span>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" disabled>
                {t("ui.common.previous", "Previous")}
              </Button>
              <Button variant="outline" size="sm" disabled>
                {t("ui.common.next", "Next")}
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 lg:grid-cols-[2fr,1fr]">
        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <CardTitle className="text-lg font-bold">
              {t(
                "ui.dev.clients.help.title",
                "Need help with OIDC configuration?",
              )}
            </CardTitle>
            <CardDescription>
              {t(
                "msg.dev.clients.help.subtitle",
                "Developer guides for Confidential/Public clients, redirect URIs, and auth methods.",
              )}
            </CardDescription>
          </CardHeader>
          <CardContent className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="flex h-12 w-12 items-center justify-center rounded-full bg-primary/15 text-primary">
                <BookOpenText className="h-6 w-6" />
              </div>
              <div>
                <p className="font-semibold">
                  {t("ui.dev.clients.help.docs_title", "Docs & Examples")}
                </p>
                <p className="text-sm text-muted-foreground">
                  {t(
                    "msg.dev.clients.help.docs_body",
                    "Includes PKCE, client_secret_basic, redirect URI validation tips.",
                  )}
                </p>
              </div>
            </div>
            <Button variant="secondary">
              {t("ui.dev.clients.help.view_guides", "View guides")}
            </Button>
          </CardContent>
        </Card>

        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <CardTitle className="text-lg font-semibold">
              {t("ui.dev.clients.owner.title", "Owner")}
            </CardTitle>
            <CardDescription>
              {t("ui.dev.clients.owner.subtitle", "Tenant admin on-call")}
            </CardDescription>
          </CardHeader>
          <CardContent className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Avatar>
                <AvatarImage
                  src="https://gitea.hmac.kr/avatars/11ed71f61227be4a9ab6c61885371d92304a4c36a5f71036890625c55daa8c41?size=512"
                  alt={t("ui.dev.clients.owner.avatar_alt", "ops user")}
                />
                <AvatarFallback>AR</AvatarFallback>
              </Avatar>
              <div>
                <p className="font-semibold">
                  {t("ui.dev.clients.owner.name", "AI Admin Bot")}
                </p>
                <p className="text-xs text-muted-foreground">
                  {t("ui.dev.clients.owner.email", "admin@brsw.kr")}
                </p>
              </div>
            </div>
            <Separator className="mx-4 hidden h-10 w-px md:block" />
            <div className="hidden flex-col items-end text-sm text-muted-foreground md:flex">
              <span>
                {t("ui.dev.clients.owner.role", "Role: Tenant Admin")}
              </span>
              <span>{t("ui.dev.clients.owner.scope", "Scope: TENANT-12")}</span>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

export default ClientsPage;
