import { useMutation, useQuery } from "@tanstack/react-query";
import {
  ArrowLeft,
  ChevronLeft,
  ChevronRight,
  Download,
  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,
  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";
import { t } from "../../lib/i18n";
import { cn } from "../../lib/utils";

function ClientConsentsPage() {
  const params = useParams();
  const clientId = params.id ?? "";
  const [subjectInput, setSubjectInput] = useState("");
  const [subject, setSubject] = useState("");
  const [statusFilter, setStatusFilter] = useState<string[]>([]);
  const [scopeFilter, setScopeFilter] = useState<string[]>([]);
  const [isAdvancedFilterOpen, setIsAdvancedFilterOpen] = useState(false);

  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, "all"),
    enabled: clientId.length > 0,
  });
  const revokeMutation = useMutation({
    mutationFn: (payload: { subject: string }) =>
      revokeConsent(payload.subject, clientId),
    onSuccess: () => {
      refetch();
    },
  });

  const handleRevoke = (sub: string) => {
    if (
      window.confirm(
        t(
          "msg.dev.clients.consents.revoke_confirm",
          "정말로 이 사용자의 권한을 철회하시겠습니까? 철회 시 사용자는 다음 접속 시 다시 동의해야 합니다.",
        ),
      )
    ) {
      revokeMutation.mutate({ subject: sub });
    }
  };

  const rows = consentsData?.items ?? [];
  const allScopes = Array.from(new Set(rows.flatMap((r) => r.grantedScopes)));
  const filteredRows = rows.filter((row) => {
    const matchStatus =
      statusFilter.length === 0 || statusFilter.includes(row.status);
    const matchScope =
      scopeFilter.length === 0 ||
      scopeFilter.some((s) => row.grantedScopes.includes(s));
    return matchStatus && matchScope;
  });

  const handleExportCSV = () => {
    if (filteredRows.length === 0) return;

    const headers = [
      t("ui.dev.clients.consents.table.user", "User"),
      t("ui.dev.clients.consents.table.tenant", "Tenant"),
      t("ui.dev.clients.table.status", "Status"),
      t("ui.dev.clients.consents.table.scopes", "Granted Scopes"),
      t("ui.dev.clients.consents.table.first_granted", "First Granted"),
      t(
        "ui.dev.clients.consents.table.last_auth",
        "Last Authenticated / Revoked",
      ),
    ];

    const csvContent = [
      headers.join(","),
      ...filteredRows.map((row) => {
        const lastAuthRevoked =
          row.status === "revoked" && row.deletedAt
            ? `${t("ui.dev.clients.consents.status_revoked", "Revoked")}: ${new Date(row.deletedAt).toLocaleString()}`
            : row.authenticatedAt
              ? new Date(row.authenticatedAt).toLocaleString()
              : "-";

        return [
          `"${row.subject} (${row.userName || ""})"`,
          `"${row.tenantName || row.tenantId || ""}"`,
          `"${row.status}"`,
          `"${row.grantedScopes.join(", ")}"`,
          `"${new Date(row.createdAt).toLocaleString()}"`,
          `"${lastAuthRevoked}"`,
        ].join(",");
      }),
    ].join("\n");

    const blob = new Blob([`\uFEFF${csvContent}`], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    const date = new Date().toISOString().split("T")[0];
    link.setAttribute("href", url);
    link.setAttribute("download", `consents_${clientId}_${date}.csv`);
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleStatusFilterChange = (status: string, checked: boolean) => {
    if (checked) {
      setStatusFilter((prev) => [...prev, status]);
    } else {
      setStatusFilter((prev) => prev.filter((s) => s !== status));
    }
  };

  const handleScopeFilterChange = (scope: string, checked: boolean) => {
    if (checked) {
      setScopeFilter((prev) => [...prev, scope]);
    } else {
      setScopeFilter((prev) => prev.filter((s) => s !== scope));
    }
  };

  const handleAllScopesChange = (checked: boolean) => {
    if (checked) {
      setScopeFilter(allScopes);
    } else {
      setScopeFilter([]);
    }
  };

  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">
                {t("ui.dev.clients.consents.breadcrumb.home", "Home")}
              </Link>
              <span>/</span>
              <Link to="/clients" className="hover:text-primary">
                {t("ui.dev.clients.consents.breadcrumb.clients", "Apps")}
              </Link>
              <span>/</span>
              <span>{clientData?.client?.name || clientId}</span>
              <span>/</span>
              <span className="text-foreground font-semibold">
                {t(
                  "ui.dev.clients.consents.breadcrumb.current",
                  "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">
                  {t("ui.dev.clients.consents.title", "User Consent Grants")}
                </p>
                <p className="text-muted-foreground">
                  {t(
                    "msg.dev.clients.consents.subtitle",
                    "OIDC Relying Party 사용자 권한을 검토·관리합니다.",
                  )}
                </p>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Badge
              variant={
                clientData?.client?.status === "active" ? "info" : "muted"
              }
            >
              {clientData?.client?.status === "active"
                ? t("ui.common.status.active", "Active")
                : t("ui.common.status.inactive", "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"
          >
            {t("ui.dev.clients.details.tab.connection", "Federation")}
          </Link>
          <span className="whitespace-nowrap border-b-2 border-primary pb-1 text-primary">
            {t("ui.dev.clients.details.tab.consents", "Consent & Users")}
          </span>
          <Link
            to={`/clients/${clientId}/settings`}
            className="whitespace-nowrap border-b-2 border-transparent text-muted-foreground hover:text-foreground"
          >
            {t("ui.dev.clients.details.tab.settings", "Settings")}
          </Link>
          <Link
            to={`/clients/${clientId}/relationships`}
            className="whitespace-nowrap border-b-2 border-transparent text-muted-foreground hover:text-foreground"
          >
            {t("ui.dev.clients.details.tab.relationships", "Relationships")}
          </Link>
        </div>
      </header>

      <Card className="glass-panel">
        <CardContent className="space-y-4">
          <div 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={t(
                    "ui.dev.clients.consents.search_placeholder",
                    "사용자 ID, 이름, 이메일로 검색",
                  )}
                  value={subjectInput}
                  onChange={(e) => setSubjectInput(e.target.value)}
                />
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Button
                variant="ghost"
                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>
              <Button
                className="shadow-sm shadow-primary/30"
                onClick={() => setSubject(subjectInput.trim())}
              >
                {t("ui.common.search", "검색")}
              </Button>
              <Button
                className="shadow-sm shadow-primary/30"
                onClick={handleExportCSV}
                disabled={filteredRows.length === 0}
              >
                <Download className="h-4 w-4" />
                {t("ui.dev.clients.consents.export_csv", "Export CSV")}
              </Button>
            </div>
          </div>

          {isAdvancedFilterOpen && (
            <div className="flex flex-col gap-4 rounded-lg bg-secondary/30 p-4 border border-border/40 animate-in fade-in slide-in-from-top-2 duration-200">
              <div className="flex flex-col gap-2">
                <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  {t("ui.dev.clients.consents.status_label", "Status:")}
                </span>
                <div className="flex flex-wrap gap-4">
                  <label className="flex items-center gap-2 text-sm cursor-pointer hover:text-foreground">
                    <input
                      type="checkbox"
                      className="rounded border-input text-primary focus:ring-primary h-4 w-4"
                      checked={statusFilter.includes("active")}
                      onChange={(e) =>
                        handleStatusFilterChange("active", e.target.checked)
                      }
                    />
                    {t("ui.common.status.active", "Active")}
                  </label>
                  <label className="flex items-center gap-2 text-sm cursor-pointer hover:text-foreground">
                    <input
                      type="checkbox"
                      className="rounded border-input text-primary focus:ring-primary h-4 w-4"
                      checked={statusFilter.includes("revoked")}
                      onChange={(e) =>
                        handleStatusFilterChange("revoked", e.target.checked)
                      }
                    />
                    {t("ui.dev.clients.consents.status_revoked", "Revoked")}
                  </label>
                </div>
              </div>

              <div className="flex flex-col gap-2">
                <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                  {t("ui.dev.clients.consents.scope_label", "Scope:")}
                </span>
                <div className="flex flex-wrap gap-4">
                  {allScopes.length > 0 && (
                    <label className="flex items-center gap-2 text-sm cursor-pointer font-bold text-primary hover:opacity-80">
                      <input
                        type="checkbox"
                        className="rounded border-input text-primary focus:ring-primary h-4 w-4"
                        checked={
                          scopeFilter.length === allScopes.length &&
                          allScopes.length > 0
                        }
                        onChange={(e) =>
                          handleAllScopesChange(e.target.checked)
                        }
                      />
                      ALL
                    </label>
                  )}
                  {allScopes.map((scope) => (
                    <label
                      key={scope}
                      className="flex items-center gap-2 text-sm cursor-pointer hover:text-foreground"
                    >
                      <input
                        type="checkbox"
                        className="rounded border-input text-primary focus:ring-primary h-4 w-4"
                        checked={scopeFilter.includes(scope)}
                        onChange={(e) =>
                          handleScopeFilterChange(scope, e.target.checked)
                        }
                      />
                      {scope}
                    </label>
                  ))}
                </div>
              </div>

              <div className="flex justify-end">
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-xs text-muted-foreground p-0 h-auto"
                  onClick={() => {
                    setStatusFilter([]);
                    setScopeFilter([]);
                  }}
                >
                  {t("ui.common.reset", "초기화")}
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card className="glass-panel">
        {error && (
          <CardContent className="text-sm text-red-500">
            {t(
              "msg.dev.clients.consents.load_error",
              "Error loading consents: {{error}}",
              {
                error: (error as Error).message,
              },
            )}
          </CardContent>
        )}
        {isLoading && (
          <CardContent className="text-sm text-muted-foreground">
            {t("msg.dev.clients.consents.loading", "Loading consents...")}
          </CardContent>
        )}

        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>
                {t("ui.dev.clients.consents.table.user", "User")}
              </TableHead>
              <TableHead>
                {t("ui.dev.clients.consents.table.tenant", "Tenant")}
              </TableHead>
              <TableHead>
                {t("ui.dev.clients.consents.table.status", "Status")}
              </TableHead>
              <TableHead>
                {t("ui.dev.clients.consents.table.scopes", "Granted Scopes")}
              </TableHead>
              <TableHead>
                {t(
                  "ui.dev.clients.consents.table.first_granted",
                  "First Granted",
                )}
              </TableHead>
              <TableHead>
                {t(
                  "ui.dev.clients.consents.table.last_auth",
                  "Last Authenticated / Revoked",
                )}
              </TableHead>
              <TableHead className="text-right">
                {t("ui.dev.clients.consents.table.action", "Action")}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredRows.length === 0 && !isLoading ? (
              <TableRow>
                <TableCell colSpan={7} className="h-24 text-center">
                  {t("msg.dev.clients.consents.empty", "No consents found.")}
                </TableCell>
              </TableRow>
            ) : (
              filteredRows.map((row) => (
                <TableRow
                  key={`${row.subject}-${row.clientId}`}
                  className={row.status === "revoked" ? "opacity-60" : ""}
                >
                  <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 ||
                            t("ui.dev.clients.consents.subject", "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 || t("ui.common.na", "N/A")}
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {row.tenantId}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    {row.status === "active" ? (
                      <Badge variant="success">
                        {t("ui.common.status.active", "Active")}
                      </Badge>
                    ) : (
                      <Badge variant="warning">
                        {t("ui.dev.clients.consents.status_revoked", "Revoked")}
                      </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.status === "revoked" && row.deletedAt ? (
                      <span className="text-destructive font-medium">
                        {t("ui.dev.clients.consents.revoked_at", "Revoked: ")}
                        {new Date(row.deletedAt).toLocaleString()}
                      </span>
                    ) : row.authenticatedAt ? (
                      new Date(row.authenticatedAt).toLocaleString()
                    ) : (
                      "-"
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    {row.status === "active" && (
                      <Button
                        variant="ghost"
                        className="text-destructive hover:bg-destructive/10"
                        onClick={() => handleRevoke(row.subject)}
                        disabled={revokeMutation.isPending}
                      >
                        {t("ui.dev.clients.consents.revoke", "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>
            {t(
              "msg.dev.clients.consents.showing",
              "Showing {{from}} to {{to}} of {{total}} users",
              {
                from: filteredRows.length > 0 ? 1 : 0,
                to: filteredRows.length,
                total: rows.length,
              },
            )}
          </p>
          <div className="flex gap-2">
            <Button variant="outline" size="icon" disabled>
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button size="sm" disabled={filteredRows.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">
              {t(
                "ui.dev.clients.consents.stats.active_grants",
                "Active Grants",
              )}
            </p>
            <CardTitle className="text-2xl font-black">
              {rows.filter((r) => r.status === "active").length}
            </CardTitle>
          </CardHeader>
        </Card>
        <Card className="glass-panel">
          <CardHeader className="pb-2">
            <p className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
              {t(
                "ui.dev.clients.consents.stats.total_scopes",
                "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">
              {t(
                "ui.dev.clients.consents.stats.avg_scopes",
                "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;
