import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import { ArrowLeft, Shield, Trash2, UserPlus, Users } from "lucide-react";
import { useState } from "react";
import { Link, useParams } from "react-router-dom";
import { commonStickyTableHeaderClass } from "../../../../../common/ui/table";
import { Badge } from "../../../components/ui/badge";
import { Button } from "../../../components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../../../components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "../../../components/ui/dialog";
import { Input } from "../../../components/ui/input";
import { Label } from "../../../components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../../../components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../../../components/ui/table";
import { toast } from "../../../components/ui/use-toast";
import {
  addGroupMember,
  assignGroupRole,
  fetchAllTenants,
  fetchGroup,
  fetchGroupRoles,
  fetchUsers,
  removeGroupMember,
  removeGroupRole,
} from "../../../lib/adminApi";
import { t } from "../../../lib/i18n";

export function UserGroupDetailPage() {
  const { tenantId, id } = useParams<{ tenantId: string; id: string }>();
  const queryClient = useQueryClient();

  const [isAddMemberOpen, setIsAddMemberOpen] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState("");
  const [searchUser, setSearchUser] = useState("");

  const [isAddRoleOpen, setIsAddRoleOpen] = useState(false);
  const [selectedTargetTenantId, setSelectedTargetTenantId] = useState("");
  const [selectedRelation, setSelectedRelation] = useState("view");

  const {
    data: currentGroup,
    isLoading: isGroupLoading,
    error,
  } = useQuery({
    queryKey: ["user-group-detail", id],
    queryFn: () => fetchGroup(tenantId ?? "", id ?? ""),
    enabled: !!id && !!tenantId,
    retry: false,
  });

  // Fetch assigned roles
  const { data: groupRoles, isLoading: isRolesLoading } = useQuery({
    queryKey: ["user-group-roles", id],
    queryFn: () => fetchGroupRoles(tenantId ?? "", id ?? ""),
    enabled: !!id && !!tenantId,
  });

  // Fetch all users for selection
  const { data: userList } = useQuery({
    queryKey: ["admin-users", searchUser],
    queryFn: () => fetchUsers(20, 0, searchUser),
    enabled: isAddMemberOpen,
  });

  // Fetch all tenants for role assignment
  const { data: tenantList } = useQuery({
    queryKey: ["admin-tenants"],
    queryFn: () => fetchAllTenants(),
    enabled: isAddRoleOpen,
  });

  const addMemberMutation = useMutation({
    mutationFn: (userId: string) =>
      addGroupMember(tenantId ?? "", id ?? "", userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-detail", id] });
      setIsAddMemberOpen(false);
      setSelectedUserId("");
      toast.success(
        t("msg.admin.groups.members.add_success", "구성원이 추가되었습니다."),
      );
    },
    onError: (error: AxiosError<{ error?: string }>) => {
      toast.error(
        error.response?.data?.error ||
          error.message ||
          t("err.common.unknown", "오류가 발생했습니다."),
      );
    },
  });

  const removeMemberMutation = useMutation({
    mutationFn: (userId: string) =>
      removeGroupMember(tenantId ?? "", id ?? "", userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-detail", id] });
      toast.success(
        t(
          "msg.admin.groups.members.remove_success",
          "구성원이 제외되었습니다.",
        ),
      );
    },
  });

  const assignRoleMutation = useMutation({
    mutationFn: () =>
      assignGroupRole(
        tenantId ?? "",
        id ?? "",
        selectedTargetTenantId,
        selectedRelation,
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-roles", id] });
      setIsAddRoleOpen(false);
      toast.success(
        t("msg.admin.groups.roles.assign_success", "역할이 할당되었습니다."),
      );
    },
    onError: (error: AxiosError<{ error?: string }>) => {
      toast.error(
        error.response?.data?.error ||
          error.message ||
          t("err.common.unknown", "오류가 발생했습니다."),
      );
    },
  });

  const removeRoleMutation = useMutation({
    mutationFn: (role: { targetTenantId: string; relation: string }) =>
      removeGroupRole(
        tenantId ?? "",
        id ?? "",
        role.targetTenantId,
        role.relation,
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-roles", id] });
      toast.success(
        t("msg.admin.groups.roles.remove_success", "역할이 회수되었습니다."),
      );
    },
  });

  if (isGroupLoading)
    return (
      <div className="flex items-center justify-center p-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        <span className="ml-3 text-muted-foreground">
          {t("msg.common.loading", "로딩 중...")}
        </span>
      </div>
    );

  if (error || !currentGroup)
    return (
      <div className="p-8 text-center space-y-4">
        <h3 className="text-xl font-semibold text-destructive">
          조직 단위를 불러올 수 없습니다
        </h3>
        <div className="p-4 bg-destructive/10 text-destructive rounded-md text-left text-sm font-mono overflow-auto max-w-xl mx-auto border border-destructive/20">
          <p>
            Error:{" "}
            {(error as AxiosError<{ error?: string }>)?.response?.data?.error ||
              (error instanceof Error ? error.message : String(error)) ||
              "Not found"}
          </p>
        </div>
        <Button
          variant="outline"
          onClick={() => {
            void queryClient.invalidateQueries({
              queryKey: ["user-group-detail", id],
            });
          }}
        >
          {t("ui.common.retry", "다시 시도")}
        </Button>
        <div className="pt-4 border-t">
          <Link
            to={`/tenants/${tenantId}/organization`}
            className="text-primary hover:underline text-sm"
          >
            {t(
              "ui.admin.groups.detail.breadcrumb_org",
              "조직 관리 목록으로 돌아가기",
            )}
          </Link>
        </div>
      </div>
    );

  return (
    <div className="space-y-8 flex flex-col h-[calc(100vh-theme(spacing.32))]">
      <header className="flex flex-wrap items-start justify-between gap-4 flex-shrink-0 sticky top-[-2.5rem] z-20 bg-background/95 backdrop-blur pt-4 pb-2 -mt-4">
        <div className="space-y-2">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <Link
              to={`/tenants/${tenantId}`}
              className="inline-flex items-center gap-2 hover:text-foreground transition-colors"
            >
              <ArrowLeft size={14} />
              {t("ui.admin.groups.detail.breadcrumb_tenant", "테넌트 상세")}
            </Link>
            <span>/</span>
            <Link
              to={`/tenants/${tenantId}/organization`}
              className="hover:text-foreground transition-colors"
            >
              {t("ui.admin.groups.detail.breadcrumb_org", "조직 관리")}
            </Link>
            <span>/</span>
            <span className="text-foreground">
              {t("ui.admin.groups.detail.breadcrumb_unit", "조직 단위")}
            </span>
          </div>
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary/10 rounded-lg">
              <Users size={24} className="text-primary" />
            </div>
            <h2 className="text-3xl font-semibold">{currentGroup.name}</h2>
            {currentGroup.unitType && (
              <Badge variant="secondary" className="h-6 font-normal">
                {currentGroup.unitType}
              </Badge>
            )}
          </div>
          <p className="text-sm text-muted-foreground">
            {currentGroup.description ||
              t("msg.common.no_description", "설명이 없습니다.")}
          </p>
        </div>
        <div className="flex gap-2">
          <Badge variant="secondary" className="font-normal">
            {t("ui.admin.groups.detail.breadcrumb_unit", "조직 단위")}
          </Badge>
        </div>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 flex-1 min-h-0">
        {/* Members Management */}
        <Card className="flex flex-col min-h-0 border-none shadow-sm bg-[var(--color-panel)] overflow-hidden">
          <CardHeader className="flex flex-row items-center justify-between flex-shrink-0">
            <div>
              <CardTitle>
                {t("ui.admin.groups.detail.members_title", "구성원 관리")}
              </CardTitle>
              <CardDescription>
                {t(
                  "ui.admin.groups.detail.members_subtitle",
                  "이 조직에 소속된 사용자를 관리합니다.",
                )}
              </CardDescription>
            </div>
            <Dialog open={isAddMemberOpen} onOpenChange={setIsAddMemberOpen}>
              <DialogTrigger asChild>
                <Button size="sm" variant="outline">
                  <UserPlus size={16} className="mr-2" />
                  {t("ui.common.add", "추가")}
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>
                    {t("ui.admin.groups.detail.members_title", "구성원 추가")}
                  </DialogTitle>
                  <DialogDescription>
                    {t(
                      "ui.admin.groups.detail.members_subtitle",
                      "사용자를 검색하여 조직 구성원으로 추가합니다.",
                    )}
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>{t("ui.common.search", "사용자 검색")}</Label>
                    <Input
                      placeholder={t(
                        "ui.admin.users.list.search_placeholder",
                        "이메일 또는 이름으로 검색...",
                      )}
                      value={searchUser}
                      onChange={(e) => setSearchUser(e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>{t("ui.common.select", "사용자 선택")}</Label>
                    <Select
                      value={selectedUserId}
                      onValueChange={setSelectedUserId}
                    >
                      <SelectTrigger>
                        <SelectValue
                          placeholder={t(
                            "ui.common.select_placeholder",
                            "사용자를 선택하세요",
                          )}
                        />
                      </SelectTrigger>
                      <SelectContent>
                        {userList?.items.map((user) => (
                          <SelectItem key={user.id} value={user.id}>
                            {user.name} ({user.email})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => setIsAddMemberOpen(false)}
                  >
                    {t("ui.common.cancel", "취소")}
                  </Button>
                  <Button
                    onClick={() => addMemberMutation.mutate(selectedUserId)}
                    disabled={!selectedUserId || addMemberMutation.isPending}
                  >
                    {t("ui.common.add", "추가")}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent className="flex-1 flex flex-col min-h-0 pt-0">
            <div className="flex-1 rounded-md border overflow-hidden flex flex-col">
              <div className="flex-1 overflow-auto relative custom-scrollbar">
                <Table>
                  <TableHeader className={commonStickyTableHeaderClass}>
                    <TableRow>
                      <TableHead className="font-bold">
                        {t("ui.admin.users.list.table.name_email", "사용자")}
                      </TableHead>
                      <TableHead className="text-right font-bold">
                        {t("ui.admin.groups.table.actions", "액션")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {!currentGroup.members ||
                    currentGroup.members.length === 0 ? (
                      <TableRow>
                        <TableCell
                          colSpan={2}
                          className="text-center py-8 text-muted-foreground"
                        >
                          {t(
                            "msg.admin.groups.members.empty",
                            "구성원이 없습니다.",
                          )}
                        </TableCell>
                      </TableRow>
                    ) : (
                      currentGroup.members.map((member) => (
                        <TableRow
                          key={member.id}
                          className="hover:bg-muted/30 transition-colors"
                        >
                          <TableCell>
                            <div className="flex items-center gap-3">
                              <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xs">
                                {member.name.charAt(0)}
                              </div>
                              <div>
                                <p className="font-medium text-sm">
                                  {member.name}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  {member.email}
                                </p>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell className="text-right">
                            <Button
                              variant="ghost"
                              size="icon"
                              className="text-destructive hover:bg-destructive/10"
                              onClick={() => {
                                if (
                                  confirm(
                                    t(
                                      "msg.admin.groups.members.remove_confirm",
                                      "제거하시겠습니까?",
                                      { name: member.name },
                                    ),
                                  )
                                ) {
                                  removeMemberMutation.mutate(member.id);
                                }
                              }}
                            >
                              <Trash2 size={14} />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Roles/Permissions Management (Keto Based) */}
        <Card className="flex flex-col min-h-0 border-none shadow-sm bg-[var(--color-panel)] overflow-hidden">
          <CardHeader className="flex flex-row items-center justify-between flex-shrink-0">
            <div>
              <CardTitle>
                {t("ui.admin.groups.detail.permissions_title", "권한 관리")}
              </CardTitle>
              <CardDescription>
                {t(
                  "ui.admin.groups.detail.permissions_subtitle",
                  "이 조직이 다른 테넌트에 가지는 역할을 정의합니다.",
                )}
              </CardDescription>
            </div>
            <Dialog open={isAddRoleOpen} onOpenChange={setIsAddRoleOpen}>
              <DialogTrigger asChild>
                <Button size="sm" variant="outline">
                  <Shield size={16} className="mr-2" />
                  {t("ui.common.assign", "할당")}
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>
                    {t(
                      "ui.admin.groups.detail.permissions_title",
                      "테넌트 역할 할당",
                    )}
                  </DialogTitle>
                  <DialogDescription>
                    {t(
                      "msg.admin.groups.roles.description",
                      "이 조직의 구성원들이 대상 테넌트에서 상속받을 역할을 선택하세요.",
                    )}
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>
                      {t("ui.admin.users.detail.form.tenant", "대상 테넌트")}
                    </Label>
                    <Select
                      value={selectedTargetTenantId}
                      onValueChange={setSelectedTargetTenantId}
                    >
                      <SelectTrigger>
                        <SelectValue
                          placeholder={t(
                            "ui.admin.tenants.list.select_placeholder",
                            "테넌트를 선택하세요",
                          )}
                        />
                      </SelectTrigger>
                      <SelectContent>
                        {tenantList?.items.map((t) => (
                          <SelectItem key={t.id} value={t.id}>
                            {t.name} ({t.slug})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>
                      {t("ui.admin.users.detail.form.role", "역할 (Relation)")}
                    </Label>
                    <Select
                      value={selectedRelation}
                      onValueChange={setSelectedRelation}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="view">View (조회 권한)</SelectItem>
                        <SelectItem value="manage">
                          Manage (운영 권한)
                        </SelectItem>
                        <SelectItem value="admins">
                          Admin (모든 권한)
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => setIsAddRoleOpen(false)}
                  >
                    {t("ui.common.cancel", "취소")}
                  </Button>
                  <Button
                    onClick={() => assignRoleMutation.mutate()}
                    disabled={
                      !selectedTargetTenantId || assignRoleMutation.isPending
                    }
                  >
                    {t("ui.common.assign", "할당")}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent className="flex-1 flex flex-col min-h-0 pt-0">
            <div className="flex-1 rounded-md border overflow-hidden flex flex-col">
              <div className="flex-1 overflow-auto relative custom-scrollbar">
                <Table>
                  <TableHeader className={commonStickyTableHeaderClass}>
                    <TableRow>
                      <TableHead className="font-bold">
                        {t("ui.admin.users.detail.form.tenant", "대상 테넌트")}
                      </TableHead>
                      <TableHead className="font-bold">
                        {t("ui.admin.users.detail.form.role", "역할")}
                      </TableHead>
                      <TableHead className="text-right font-bold">
                        {t("ui.admin.groups.table.actions", "액션")}
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {isRolesLoading ? (
                      <TableRow>
                        <TableCell colSpan={3} className="text-center py-8">
                          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary mx-auto" />
                        </TableCell>
                      </TableRow>
                    ) : !groupRoles || groupRoles.length === 0 ? (
                      <TableRow>
                        <TableCell
                          colSpan={3}
                          className="text-center py-8 text-muted-foreground"
                        >
                          {t(
                            "msg.admin.groups.roles.empty",
                            "할당된 역할이 없습니다.",
                          )}
                        </TableCell>
                      </TableRow>
                    ) : (
                      groupRoles.map((role, idx) => (
                        <TableRow
                          key={`${role.tenantId}-${role.relation}-${idx}`}
                          className="hover:bg-muted/30 transition-colors"
                        >
                          <TableCell>
                            <div className="font-medium text-sm">
                              {role.tenantName || role.tenantId}
                            </div>
                          </TableCell>
                          <TableCell>
                            <Badge
                              variant="outline"
                              className="capitalize font-normal"
                            >
                              {role.relation}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">
                            <Button
                              variant="ghost"
                              size="icon"
                              className="text-destructive hover:bg-destructive/10"
                              onClick={() => {
                                if (
                                  confirm(
                                    t("msg.admin.groups.roles.remove_confirm"),
                                  )
                                ) {
                                  removeRoleMutation.mutate({
                                    targetTenantId: role.tenantId,
                                    relation: role.relation,
                                  });
                                }
                              }}
                            >
                              <Trash2 size={14} />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
