import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import {
  Activity,
  BookOpenText,
  Copy,
  Laptop,
  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 { 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 {
  deleteClient,
  fetchClients,
  updateClientStatus,
} from "../../lib/devApi";
import { cn } from "../../lib/utils";
import { CopyButton } from "../../components/ui/copy-button";
import { toast } from "../../components/ui/use-toast";

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" ? "활성화" : "비활성화";
      toast(`클라이언트가 ${statusText}되었습니다.`);
      queryClient.invalidateQueries({ queryKey: ["clients"] });
    },
    onError: (error: AxiosError<{ error?: string }>) => {
      const errMsg =
        error.response?.data?.error ??
        error.message ??
        "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
  const stats = [
    {
      label: "총 클라이언트",
      value: totalClients.toString(),
      delta: "Realtime",
      tone: "up" as const,
    },
    {
      label: "활성 세션",
      value: "-",
      delta: "Not impl",
      tone: "stable" as const,
    },
    {
      label: "인증 실패 (24h)",
      value: "0",
      delta: "Stable",
      tone: "stable" as const,
    },
  ];

  if (isLoading) {
    return <div className="p-8 text-center">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">
        Error loading clients: {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">
                RP registry
              </p>
              <CardTitle className="text-3xl font-black tracking-tight">
                Relying Parties
              </CardTitle>
              <CardDescription>
                OIDC 클라이언트, 인증 방식, 리다이렉트 URI, 비밀키 재발행을 감사
                로그와 함께 관리합니다.
              </CardDescription>
            </div>
            <div className="hidden items-center gap-2 md:flex">
              <Button variant="outline" size="sm">
                비밀키 재발행
              </Button>
              <Button
                size="sm"
                className="shadow-lg shadow-primary/30"
                onClick={() => navigate("/clients/new")}
              >
                <Plus className="h-4 w-4" />새 클라이언트
              </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="클라이언트 이름/ID로 검색..."
              />
            </div>
            <div className="flex items-center justify-end gap-2 md:justify-start">
              <Badge variant="muted">테넌트: 선택됨</Badge>
              <Badge variant="success">관리자 세션</Badge>
            </div>
          </div>
        </CardHeader>
        <CardContent className="pt-0">
          <div className="grid gap-4 md:grid-cols-3">
            {stats.map((item) => (
              <Card key={item.label} className="border border-border/60">
                <CardHeader className="pb-2">
                  <CardDescription>{item.label}</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 === "down" &&
                          "bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-200",
                        item.tone === "stable" && "bg-muted/40 text-foreground",
                      )}
                    >
                      {item.delta}
                    </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">
              클라이언트 목록
            </CardTitle>
            <div className="flex items-center gap-2 md:hidden">
              <Button variant="outline" size="sm">
                비밀키 재발행
              </Button>
              <Button size="sm" onClick={() => navigate("/clients/new")}>
                <Plus className="h-4 w-4" />새 클라이언트
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>애플리케이션</TableHead>
                <TableHead>Client ID</TableHead>
                <TableHead>유형</TableHead>
                <TableHead>상태</TableHead>
                <TableHead>생성일</TableHead>
                <TableHead className="text-right">액션</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 || "Untitled"}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          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="Copy client id"
                        onCopy={() => toast("클라이언트 ID가 복사되었습니다.")}
                      />
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={
                        client.type === "confidential" ? "success" : "muted"
                      }
                    >
                      {client.type === "confidential"
                        ? "기밀(Confidential)"
                        : "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" ? "활성" : "비활성"}
                      </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}`}>Edit</Link>
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-muted-foreground hover:text-destructive"
                        onClick={() => deleteMutation.mutate(client.id)}
                      >
                        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>
              Showing {clients.length} of {totalClients} clients
            </span>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" disabled>
                Previous
              </Button>
              <Button variant="outline" size="sm" disabled>
                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">
              Need help with OIDC configuration?
            </CardTitle>
            <CardDescription>
              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">Docs &amp; Examples</p>
                <p className="text-sm text-muted-foreground">
                  Includes PKCE, client_secret_basic, redirect URI validation
                  tips.
                </p>
              </div>
            </div>
            <Button variant="secondary">View guides</Button>
          </CardContent>
        </Card>

        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <CardTitle className="text-lg font-semibold">Owner</CardTitle>
            <CardDescription>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="ops user"
                />
                <AvatarFallback>AR</AvatarFallback>
              </Avatar>
              <div>
                <p className="font-semibold">AI Admin Bot</p>
                <p className="text-xs text-muted-foreground">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>Role: Tenant Admin</span>
              <span>Scope: TENANT-12</span>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

export default ClientsPage;
