import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, Plus, Shield, Trash2, UserPlus, Users } 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 {
  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 {
  addGroupMember,
  assignGroupRole,
  fetchGroup,
  fetchGroupRoles,
  fetchTenants,
  fetchUsers,
  removeGroupMember,
  removeGroupRole,
} from "../../../lib/adminApi";

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");

  // Fetch specific group details
  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: () => fetchTenants(100, 0),
    enabled: isAddRoleOpen,
  });

  const addMemberMutation = useMutation({
    mutationFn: (userId: string) => addGroupMember(tenantId!, id!, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-detail", id] });
      setIsAddMemberOpen(false);
      setSelectedUserId("");
      alert("Member added successfully");
    },
    onError: (error: any) => {
      alert(error.message || "Failed to add member");
    },
  });

  const removeMemberMutation = useMutation({
    mutationFn: (userId: string) => removeGroupMember(tenantId!, id!, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-detail", id] });
      alert("Member removed successfully");
    },
  });

  const assignRoleMutation = useMutation({
    mutationFn: () =>
      assignGroupRole(
        tenantId!,
        id!,
        selectedTargetTenantId,
        selectedRelation,
      ),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-roles", id] });
      setIsAddRoleOpen(false);
      alert(`Role '${selectedRelation}' assigned successfully`);
    },
    onError: (error: any) => {
      alert(error.message || "Failed to assign role");
    },
  });

  const removeRoleMutation = useMutation({
    mutationFn: (role: { targetTenantId: string; relation: string }) =>
      removeGroupRole(tenantId!, id!, role.targetTenantId, role.relation),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["user-group-roles", id] });
      alert("Role removed successfully");
    },
  });

  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"></div>
      <span className="ml-3 text-muted-foreground">Loading group details...</span>
    </div>
  );

  if (error || !currentGroup) return (
    <div className="p-8 text-center space-y-4">
      <h3 className="text-xl font-semibold text-destructive">Could not load group</h3>
      <div className="p-4 bg-red-50 text-red-700 rounded-md text-left text-sm font-mono overflow-auto max-w-xl mx-auto border border-red-100">
        <p>Error: {(error as any)?.response?.data?.error || (error as any)?.message || "Not found"}</p>
        <p className="mt-2 text-red-500 opacity-70">Path: /admin/tenants/{tenantId}/user-groups/{id}</p>
      </div>
      <p className="text-muted-foreground pt-2">The group ID might be invalid or you don't have sufficient permissions.</p>
      <Button variant="outline" onClick={() => window.location.reload()}>Retry</Button>
      <div className="pt-4 border-t">
        <Link to={`/tenants/${tenantId}/user-groups`} className="text-primary hover:underline text-sm">
          Return to Group List
        </Link>
      </div>
    </div>
  );

  return (
    <div className="space-y-8">
      <header className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-2">
          <div className="flex items-center gap-2 text-sm text-[var(--color-muted)]">
            <Link
              to={`/tenants/${tenantId}`}
              className="inline-flex items-center gap-2 hover:text-foreground transition-colors"
            >
              <ArrowLeft size={14} />
              Tenant Detail
            </Link>
            <span>/</span>
            <span className="text-foreground">User Group</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>
          </div>
          <p className="text-sm text-[var(--color-muted)]">
            {currentGroup.description || "No description provided."}
          </p>
        </div>
        <div className="flex gap-2">
           <Badge variant="outline">User Group</Badge>
           <Badge variant="muted">Tenant: {tenantId?.split('-')[0]}...</Badge>
        </div>
      </header>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Members Management */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Members</CardTitle>
              <CardDescription>Manage users in this group.</CardDescription>
            </div>
            <Dialog open={isAddMemberOpen} onOpenChange={setIsAddMemberOpen}>
              <DialogTrigger asChild>
                <Button size="sm" variant="outline">
                  <UserPlus size={16} className="mr-2" />
                  Add Member
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Add Member</DialogTitle>
                  <DialogDescription>
                    Select a user to add to this group.
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>Search User</Label>
                    <Input 
                      placeholder="Search by email or name..." 
                      value={searchUser}
                      onChange={(e) => setSearchUser(e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Select User</Label>
                    <Select value={selectedUserId} onValueChange={setSelectedUserId}>
                      <SelectTrigger>
                        <SelectValue placeholder="Choose a user" />
                      </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)}>
                    Cancel
                  </Button>
                  <Button 
                    onClick={() => addMemberMutation.mutate(selectedUserId)}
                    disabled={!selectedUserId || addMemberMutation.isPending}
                  >
                    Add
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>User</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {!currentGroup.members || currentGroup.members.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={2} className="text-center py-4 text-muted-foreground">
                      No members in this group.
                    </TableCell>
                  </TableRow>
                ) : (
                  currentGroup.members.map((member) => (
                    <TableRow key={member.id}>
                      <TableCell>
                        <div>
                          <p className="font-medium">{member.name}</p>
                          <p className="text-xs text-muted-foreground">{member.email}</p>
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          className="text-destructive"
                          onClick={() => removeMemberMutation.mutate(member.id)}
                        >
                          <Trash2 size={14} />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Roles/Permissions Management (Keto Based) */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <div>
              <CardTitle>Permissions</CardTitle>
              <CardDescription>Tenant roles assigned to this group.</CardDescription>
            </div>
            <Dialog open={isAddRoleOpen} onOpenChange={setIsAddRoleOpen}>
              <DialogTrigger asChild>
                <Button size="sm" variant="outline">
                  <Shield size={16} className="mr-2" />
                  Assign Role
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Assign Tenant Role</DialogTitle>
                  <DialogDescription>
                    Members of this group will inherit this role on the target tenant.
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                   <div className="space-y-2">
                    <Label>Target Tenant</Label>
                    <Select value={selectedTargetTenantId} onValueChange={setSelectedTargetTenantId}>
                      <SelectTrigger>
                        <SelectValue placeholder="Select target tenant" />
                      </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>Role (Relation)</Label>
                    <Select value={selectedRelation} onValueChange={setSelectedRelation}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="view">View (Read-only)</SelectItem>
                        <SelectItem value="manage">Manage (Read/Write)</SelectItem>
                        <SelectItem value="admins">Admin (Full Control)</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsAddRoleOpen(false)}>
                    Cancel
                  </Button>
                  <Button 
                    onClick={() => assignRoleMutation.mutate()}
                    disabled={!selectedTargetTenantId || assignRoleMutation.isPending}
                  >
                    Assign
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Target Tenant</TableHead>
                  <TableHead>Role</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isRolesLoading ? (
                  <TableRow><TableCell colSpan={3} className="text-center">Loading...</TableCell></TableRow>
                ) : !groupRoles || groupRoles.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={3} className="text-center py-4 text-muted-foreground">
                      No roles assigned.
                    </TableCell>
                  </TableRow>
                ) : (
                  groupRoles.map((role, idx) => (
                    <TableRow key={`${role.tenantId}-${role.relation}-${idx}`}>
                      <TableCell>
                        <div className="font-medium">{role.tenantName || role.tenantId}</div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="capitalize">{role.relation}</Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          className="text-destructive"
                          onClick={() => removeRoleMutation.mutate({ targetTenantId: role.tenantId, relation: role.relation })}
                        >
                          <Trash2 size={14} />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
