import { useQuery } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import {
  BookOpenText,
  Filter,
  Plus,
  Search,
  ServerCog,
  ShieldHalf,
} from "lucide-react";
import { useState } from "react";
import { useAuth } from "react-oidc-context";
import { Link, useNavigate } from "react-router-dom";
import { SearchFilterBar } from "../../../../common/ui/search-filter-bar";
import { ForbiddenMessage } from "../../components/common/ForbiddenMessage";
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 { Input } from "../../components/ui/input";
import { Separator } from "../../components/ui/separator";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../components/ui/table";
import { fetchClients, fetchDevStats } from "../../lib/devApi";
import { t } from "../../lib/i18n";
import { cn } from "../../lib/utils";

function ClientsPage() {
  const navigate = useNavigate();
  const auth = useAuth();
  const hasAccessToken = Boolean(auth.user?.access_token);

  const {
    data,
    isLoading: isLoadingClients,
    error: clientError,
  } = useQuery({
    queryKey: ["clients"],
    queryFn: fetchClients,
    enabled: hasAccessToken,
  });

  const { data: statsData, isLoading: isLoadingStats } = useQuery({
    queryKey: ["dev-stats"],
    queryFn: fetchDevStats,
    enabled: hasAccessToken,
  });

  const [searchQuery, setSearchQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [isAdvancedFilterOpen, setIsAdvancedFilterOpen] = useState(false);

  const clients = data?.items || [];

  const filteredClients = clients.filter((client) => {
    const matchesSearch =
      !searchQuery ||
      client.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      client.id.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesType = typeFilter === "all" || client.type === typeFilter;
    const matchesStatus =
      statusFilter === "all" || client.status === statusFilter;
    return matchesSearch && matchesType && matchesStatus;
  });

  const totalClients = statsData?.total_clients ?? clients.length;
  const activeSessions = statsData?.active_sessions ?? 0;
  const authFailures = statsData?.auth_failures_24h ?? 0;

  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: "Total Applications",
      value: totalClients.toString(),
      deltaKey: "ui.dev.clients.stats.realtime",
      deltaFallback: "Realtime",
      tone: "up" as const,
    },
    {
      labelKey: "ui.dev.clients.stats.active_sessions",
      labelFallback: "Active Sessions",
      value: activeSessions.toString(),
      deltaKey: "ui.dev.clients.stats.realtime",
      deltaFallback: "Realtime",
      tone: "up" as const,
    },
    {
      labelKey: "ui.dev.clients.stats.auth_failures",
      labelFallback: "Auth Failures (24h)",
      value: authFailures.toString(),
      deltaKey:
        authFailures > 0
          ? "ui.dev.clients.stats.alert"
          : "ui.dev.clients.stats.stable",
      deltaFallback: authFailures > 0 ? "Check Logs" : "Stable",
      tone: authFailures > 0 ? ("down" as const) : ("stable" as const),
    },
  ];

  const isLoading = isLoadingClients || isLoadingStats;

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

  if (clientError) {
    const axiosError = clientError as AxiosError<{ error?: string }>;
    if (axiosError.response?.status === 403) {
      return <ForbiddenMessage resourceToken="clients" />;
    }
    const errMsg =
      axiosError.response?.data?.error ?? (clientError 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", "연동 앱")}
              </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>
          <SearchFilterBar
            className="mt-4"
            primary={
              <div className="relative flex-1">
                <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로 검색...",
                  )}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            }
            actions={
              <>
                <Button
                  variant="ghost"
                  size="sm"
                  className={cn(
                    "gap-1 text-muted-foreground",
                    isAdvancedFilterOpen && "text-primary bg-primary/10",
                  )}
                  onClick={() => setIsAdvancedFilterOpen(!isAdvancedFilterOpen)}
                >
                  <Filter className="h-4 w-4" />
                  {t(
                    "ui.dev.clients.consents.filters.advanced",
                    "Advanced Filters",
                  )}
                </Button>
                <div className="hidden items-center gap-2 md:flex">
                  <Badge variant="muted">
                    {t(
                      "ui.dev.clients.badge.tenant_selected",
                      "테넌트: 선택됨",
                    )}
                  </Badge>
                  <Badge variant="success">
                    {t("ui.dev.clients.badge.admin_session", "관리자 세션")}
                  </Badge>
                </div>
              </>
            }
            advancedOpen={isAdvancedFilterOpen}
            advanced={
              <div className="flex flex-wrap items-center gap-6">
                <div className="flex items-center gap-2">
                  <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground whitespace-nowrap">
                    {t("ui.dev.clients.filter.type_label", "Type:")}
                  </span>
                  <select
                    className="h-9 min-w-[140px] rounded-md border border-input bg-background px-3 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/30"
                    value={typeFilter}
                    onChange={(e) => setTypeFilter(e.target.value)}
                  >
                    <option value="all">
                      {t("ui.dev.clients.filter.type_all", "모든 유형")}
                    </option>
                    <option value="private">
                      {t("ui.dev.clients.type.private", "Server side App")}
                    </option>
                    <option value="pkce">
                      {t("ui.dev.clients.type.pkce", "PKCE")}
                    </option>
                  </select>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground whitespace-nowrap">
                    {t("ui.dev.clients.consents.status_label", "Status:")}
                  </span>
                  <select
                    className="h-9 min-w-[140px] rounded-md border border-input bg-background px-3 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/30"
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                  >
                    <option value="all">
                      {t("ui.dev.clients.filter.status_all", "모든 상태")}
                    </option>
                    <option value="active">
                      {t("ui.common.status.active", "Active")}
                    </option>
                    <option value="inactive">
                      {t("ui.common.status.inactive", "Inactive")}
                    </option>
                  </select>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  className="ml-auto text-xs text-muted-foreground"
                  onClick={() => {
                    setTypeFilter("all");
                    setStatusFilter("all");
                  }}
                >
                  {t("ui.common.reset", "초기화")}
                </Button>
              </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"
                          : item.tone === "down"
                            ? "warning"
                            : "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>
              {filteredClients.map((client) => (
                <TableRow key={client.id} className="bg-card/40">
                  <TableCell>
                    <Link
                      to={`/clients/${client.id}`}
                      className="flex items-center gap-3 transition-colors hover:text-primary"
                    >
                      <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
                        {client.type === "private" ? (
                          <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>
                    </Link>
                  </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>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={client.type === "private" ? "success" : "muted"}
                    >
                      {client.type === "private"
                        ? t("ui.dev.clients.type.private", "Server side App")
                        : client.metadata?.headless_login_enabled
                          ? t(
                              "ui.dev.clients.type.pkce_headless",
                              "PKCE (Headless Login)",
                            )
                          : t("ui.dev.clients.type.pkce", "PKCE")}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={client.status === "active" ? "info" : "muted"}
                      className="px-3 py-1 text-xs uppercase"
                    >
                      {client.status === "active"
                        ? t("ui.common.status.active", "Active")
                        : t("ui.common.status.inactive", "Inactive")}
                    </Badge>
                  </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.view", "View")}
                        </Link>
                      </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: filteredClients.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;
