import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ArrowLeft, Mail, Shield, X } from "lucide-react";
import { toast } from "sonner";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Muted } from "@/components/ui/typography";
import { WindowControls } from "@/components/window-controls";
import { useNetworks } from "@/hooks/use-networks";
import {
  useNetworkInvitations,
  useInviteMembers,
  useRevokeInvitation,
} from "@/hooks/use-invitations";
import { useAuthStore } from "@/stores/auth-store";
import type { Human } from "@/api/types";

function MemberRow({
  human,
  isAdmin,
}: {
  human: Human;
  isAdmin: boolean;
}) {
  const initials = human.email_prefix.slice(0, 2).toUpperCase();

  return (
    <div className="flex w-full items-center gap-3 px-4 py-3">
      <Avatar>
        <AvatarFallback className="bg-primary/10 text-primary font-medium">
          {initials}
        </AvatarFallback>
      </Avatar>
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm font-medium">{human.email_prefix}</p>
        <Muted className="text-xs">{human.email}</Muted>
      </div>
      {isAdmin && (
        <Badge variant="secondary" className="shrink-0">
          <Shield className="mr-1 size-3" />
          Admin
        </Badge>
      )}
    </div>
  );
}

function InviteForm({ networkId }: { networkId: string }) {
  const [email, setEmail] = useState("");
  const inviteMembers = useInviteMembers(networkId);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed) return;

    inviteMembers.mutate([trimmed], {
      onSuccess: () => {
        toast.success(`Invitation sent to ${trimmed}`);
        setEmail("");
      },
      onError: (err) => {
        toast.error(err.message || "Failed to send invitation");
      },
    });
  };

  return (
    <form onSubmit={handleSubmit} className="flex items-center gap-2 px-4 py-3">
      <Input
        type="email"
        placeholder="Email address"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        className="flex-1"
      />
      <Button
        type="submit"
        size="sm"
        disabled={!email.trim() || inviteMembers.isPending}
      >
        {inviteMembers.isPending ? "Sending..." : "Invite"}
      </Button>
    </form>
  );
}

function PendingInvitationRow({
  email,
  networkId,
}: {
  email: string;
  networkId: string;
}) {
  const revokeInvitation = useRevokeInvitation(networkId);

  const handleRevoke = () => {
    revokeInvitation.mutate(email, {
      onSuccess: () => {
        toast.success(`Invitation to ${email} revoked`);
      },
      onError: (err) => {
        toast.error(err.message || "Failed to revoke invitation");
      },
    });
  };

  return (
    <div className="flex w-full items-center gap-3 px-4 py-3">
      <span className="text-muted-foreground flex size-10 items-center justify-center">
        <Mail className="size-4" />
      </span>
      <div className="min-w-0 flex-1">
        <p className="truncate text-sm">{email}</p>
        <Muted className="text-xs">Pending</Muted>
      </div>
      <Button
        variant="ghost"
        size="icon-sm"
        onClick={handleRevoke}
        disabled={revokeInvitation.isPending}
        className="text-muted-foreground hover:text-destructive shrink-0"
      >
        <X className="size-3.5" />
      </Button>
    </div>
  );
}

function SettingsGroup({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <p className="text-muted-foreground px-4 pb-1 pt-4 text-xs font-medium uppercase tracking-wider">
        {title}
      </p>
      <div>{children}</div>
    </div>
  );
}

export default function NetworkSettingsPage() {
  const navigate = useNavigate();
  const { networkId } = useParams<{ networkId: string }>();
  const { data: networks } = useNetworks();
  const network = networks?.find((n) => n.id === networkId);
  const { data: invitations } = useNetworkInvitations(networkId!);
  const currentUser = useAuthStore((s) => s.user);
  const isAdmin = currentUser?.id === network?.admin_human.id;

  const networkName = network?.name ?? "Network";

  return (
    <div className="flex h-screen flex-col">
      <div className="drag-region flex items-center gap-3 border-b px-3 py-1">
        <WindowControls />
        <Button
          variant="ghost"
          size="sm"
          className="no-drag text-muted-foreground"
          onClick={() => navigate(`/${networkId}`)}
        >
          <ArrowLeft className="size-3.5" />
        </Button>
        <span className="text-sm font-medium">{networkName}</span>
        <div className="flex-1" />
      </div>

      <ScrollArea className="flex-1">
        <SettingsGroup title="Members">
          {network?.humans.map((human, index) => (
            <div key={human.id}>
              <MemberRow
                human={human}
                isAdmin={human.id === network.admin_human.id}
              />
              {index < network.humans.length - 1 && (
                <Separator className="mx-4" />
              )}
            </div>
          ))}
        </SettingsGroup>

        <Separator className="mt-4" />

        {isAdmin && network && (
          <>
            <SettingsGroup title="Invite">
              <InviteForm networkId={networkId!} />
            </SettingsGroup>

            <Separator className="mt-4" />

            <SettingsGroup title="Pending Invitations">
              {invitations && invitations.length > 0 ? (
                invitations.map((inv, index) => (
                  <div key={inv.email}>
                    <PendingInvitationRow
                      email={inv.email}
                      networkId={networkId!}
                    />
                    {index < invitations.length - 1 && (
                      <Separator className="mx-4" />
                    )}
                  </div>
                ))
              ) : (
                <p className="text-muted-foreground px-4 py-3 text-sm">
                  No pending invitations
                </p>
              )}
            </SettingsGroup>
          </>
        )}
      </ScrollArea>
    </div>
  );
}
