import { useMutation, useQuery } from "@tanstack/react-query";
import {
  ArrowLeft,
  ChevronLeft,
  ChevronRight,
  Filter,
  Search,
} from "lucide-react";
import { useState } from "react";
import { Link, useParams } from "react-router-dom";
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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../components/ui/table";
import { fetchClient, fetchConsents, revokeConsent } from "../../lib/devApi";

function ClientConsentsPage() {
  const params = useParams();
  const clientId = params.id ?? "";
  const [subjectInput, setSubjectInput] = useState("");
  const [subject, setSubject] = useState("");
  const { data: clientData } = useQuery({
    queryKey: ["client", clientId],
    queryFn: () => fetchClient(clientId),
    enabled: clientId.length > 0,
  });
  const {
    data: consentsData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["consents", clientId, subject],
    queryFn: () => fetchConsents(subject, clientId),
    enabled: clientId.length > 0, // Removed subject.length > 0 check
  });
  const revokeMutation = useMutation({
    mutationFn: (payload: { subject: string }) =>
      revokeConsent(payload.subject, clientId),
    onSuccess: () => {
      refetch();
    },
  });

  const rows = consentsData?.items ?? [];

  return (
    <div className="space-y-8">
      <header className="space-y-4">
        <div className="flex flex-wrap justify-between gap-4">
          <div className="space-y-2">
            <nav className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
              <Link to="/" className="hover:text-primary">
                Home
              </Link>
              <span>/</span>
              <Link to="/clients" className="hover:text-primary">
                Clients
              </Link>
              <span>/</span>
              <span>{clientData?.client?.name || clientId}</span>
              <span>/</span>
              <span className="text-foreground font-semibold">
                User Consent Grants
              </span>
            </nav>
            <div className="flex items-center gap-2">
              <Button variant="ghost" size="icon" asChild>
                <Link to={`/clients/${clientId}`}>
                  <ArrowLeft className="h-4 w-4" />
                </Link>
              </Button>
              <div>
                <p className="text-3xl font-black leading-tight">
                  User Consent Grants
                </p>
                <p className="text-muted-foreground">
                  OIDC Relying Party 사용자 권한을 검토·관리합니다.
                </p>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Badge
              variant={
                clientData?.client?.status === "active" ? "success" : "muted"
              }
            >
              {clientData?.client?.status === "active" ? "Active" : "Inactive"}
            </Badge>
          </div>
        </div>
        <div className="flex gap-6 overflow-x-auto border-b border-border pb-3 text-sm font-bold">
          <Link
            to={`/clients/${clientId}`}
            className="whitespace-nowrap border-b-2 border-transparent text-muted-foreground hover:text-foreground"
          >
            Connection
          </Link>
          <span className="whitespace-nowrap border-b-2 border-primary pb-1 text-primary">
            Consent &amp; Users
          </span>
          <Link
            to={`/clients/${clientId}/settings`}
            className="whitespace-nowrap border-b-2 border-transparent text-muted-foreground hover:text-foreground"
          >
            Settings
          </Link>
        </div>
      </header>

      <Card className="glass-panel">
        <CardContent className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex flex-wrap items-center gap-4 flex-1">
            <div className="relative w-full max-w-md">
              <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, 이름, 이메일로 검색"
                value={subjectInput}
                onChange={(e) => setSubjectInput(e.target.value)}
              />
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                Status:
              </span>
              <select className="h-10 rounded-lg border border-input bg-background px-3 text-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30">
                <option>All Statuses</option>
                <option selected>Active</option>
                <option>Revoked</option>
              </select>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Button variant="ghost" className="gap-1 text-muted-foreground">
              <Filter className="h-4 w-4" />
              Advanced Filters
            </Button>
            <Button
              className="shadow-sm shadow-primary/30"
              onClick={() => setSubject(subjectInput.trim())}
            >
              검색
            </Button>
            <Button className="shadow-sm shadow-primary/30">Export CSV</Button>
          </div>
        </CardContent>
      </Card>

      <Card className="glass-panel">
        {error && (
          <CardContent className="text-sm text-red-500">
            Error loading consents: {(error as Error).message}
          </CardContent>
        )}
        {isLoading && (
          <CardContent className="text-sm text-muted-foreground">
            Loading consents...
          </CardContent>
        )}
        
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>User</TableHead>
              <TableHead>Tenant</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Granted Scopes</TableHead>
              <TableHead>First Granted</TableHead>
              <TableHead>Last Authenticated</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 && !isLoading ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center">
                  No consents found.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((row) => (
                <TableRow key={`${row.subject}-${row.clientId}`}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-xs font-bold text-primary">
                        {(row.userName || row.subject).slice(0, 2).toUpperCase()}
                      </div>
                      <div className="flex flex-col">
                        <span className="text-sm font-semibold">
                          {row.userName || "Subject"}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          {row.subject}
                        </span>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-col">
                      <span className="text-sm font-semibold">
                        {row.tenantName || "N/A"}
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {row.tenantId}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="success">Active</Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {row.grantedScopes.map((scope) => (
                        <Badge
                          key={scope}
                          variant="muted"
                          className="border bg-muted/40 text-foreground"
                        >
                          {scope}
                        </Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {new Date(row.createdAt).toLocaleString()}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {row.authenticatedAt
                      ? new Date(row.authenticatedAt).toLocaleString()
                      : "-"}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button
                      variant="ghost"
                      className="text-destructive"
                      onClick={() =>
                        revokeMutation.mutate({ subject: row.subject })
                      }
                    >
                      Revoke
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
        <CardContent className="flex items-center justify-between border-t border-border bg-muted/10 px-6 py-4 text-sm text-muted-foreground">
          <p>
            Showing <span className="font-semibold text-foreground">{rows.length > 0 ? 1 : 0}</span> to{" "}
            <span className="font-semibold text-foreground">{rows.length}</span> of{" "}
            <span className="font-semibold text-foreground">{rows.length}</span> users
          </p>
          <div className="flex gap-2">
            <Button variant="outline" size="icon" disabled>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button size="sm" disabled={rows.length === 0}>1</Button>
            <Button variant="outline" size="icon" disabled>
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-6 md:grid-cols-3">
        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Active Grants
            </p>
            <CardTitle className="text-2xl font-black">{rows.length}</CardTitle>
          </CardHeader>
        </Card>
        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Total Scopes Issued
            </p>
            <CardTitle className="text-2xl font-black">
              {rows.reduce((acc, row) => acc + row.grantedScopes.length, 0)}
            </CardTitle>
          </CardHeader>
        </Card>
        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              Avg. Scopes per User
            </p>
            <CardTitle className="text-2xl font-black">
              {rows.length > 0
                ? (
                    rows.reduce((acc, row) => acc + row.grantedScopes.length, 0) /
                    rows.length
                  ).toFixed(1)
                : "0.0"}
            </CardTitle>
          </CardHeader>
        </Card>
      </div>
    </div>
  );
}

export default ClientConsentsPage;
