import { useEffect, useState, type FormEvent, type ReactNode } from "react";
import { Copy, Plus, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getStoredToken, type AuthUser } from "@/lib/auth";
import { createInvitation, listInvitations, listUsers, type Invitation } from "@/lib/users";
import type { Client } from "@/lib/clients";

type UsersViewProps = {
  clients: Client[];
};

const roleLabels: Record<AuthUser["role"] | Invitation["role"], string> = {
  super_admin: "Super-admin",
  agency_user: "Agência",
  client_viewer: "Cliente",
};

export function UsersView({ clients }: UsersViewProps) {
  const [users, setUsers] = useState<AuthUser[]>([]);
  const [invitations, setInvitations] = useState<Invitation[]>([]);
  const [email, setEmail] = useState("");
  const [role, setRole] = useState<Invitation["role"]>("agency_user");
  const [clientId, setClientId] = useState("");
  const [createdURL, setCreatedURL] = useState("");
  const [inviteStatus, setInviteStatus] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    void refresh();
  }, []);

  async function refresh() {
    const token = getStoredToken();
    if (!token) return;

    setIsLoading(true);
    setError("");
    try {
      const [loadedUsers, loadedInvitations] = await Promise.all([listUsers(token), listInvitations(token)]);
      setUsers(loadedUsers);
      setInvitations(loadedInvitations);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Não foi possível carregar acessos.");
    } finally {
      setIsLoading(false);
    }
  }

  async function handleInvite(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const token = getStoredToken();
    if (!token) return;

    setIsSubmitting(true);
    setError("");
    setCreatedURL("");
    setInviteStatus("");
    try {
      const invitation = await createInvitation(token, {
        email,
        role,
        client_id: role === "client_viewer" ? clientId : undefined,
      });
      setInvitations((current) => [invitation, ...current]);
      setEmail("");
      setClientId("");
      setCreatedURL(invitation.invitation_url ?? "");
      setInviteStatus(
        invitation.email_sent
          ? "Convite criado e e-mail enviado."
          : invitation.email_error || "Convite criado. Configure o SMTP para enviar por e-mail ou copie o link abaixo.",
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : "Não foi possível criar o convite.");
    } finally {
      setIsSubmitting(false);
    }
  }

  async function copyInvitationURL() {
    if (!createdURL) return;
    await navigator.clipboard.writeText(createdURL);
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Gestão de Acessos</h1>
          <p className="text-sm text-muted-foreground mt-1">Gerencie usuários da agência e clientes.</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Convidar usuário</CardTitle>
        </CardHeader>
        <CardContent>
          <form className="grid gap-3 md:grid-cols-[1fr_180px_220px_auto]" onSubmit={handleInvite}>
            <div className="grid gap-2">
              <Label htmlFor="invite-email">E-mail</Label>
              <Input
                id="invite-email"
                type="email"
                placeholder="nome@empresa.com.br"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="invite-role">Perfil</Label>
              <select
                id="invite-role"
                className="h-9 rounded-lg border border-input bg-background px-3 text-sm"
                value={role}
                onChange={(event) => setRole(event.target.value as Invitation["role"])}
              >
                <option value="agency_user">Agência</option>
                <option value="client_viewer">Cliente</option>
              </select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="invite-client">Cliente</Label>
              <select
                id="invite-client"
                className="h-9 rounded-lg border border-input bg-background px-3 text-sm disabled:opacity-60"
                value={clientId}
                onChange={(event) => setClientId(event.target.value)}
                disabled={role !== "client_viewer"}
                required={role === "client_viewer"}
              >
                <option value="">Selecione</option>
                {clients.map((client) => (
                  <option key={client.id} value={client.id}>{client.name}</option>
                ))}
              </select>
            </div>

            <Button className="md:self-end" type="submit" disabled={isSubmitting || (role === "client_viewer" && !clientId)}>
              <Plus className="mr-2 h-4 w-4" />
              {isSubmitting ? "Criando..." : "Convidar"}
            </Button>
          </form>

          {inviteStatus && (
            <div className="mt-4 rounded-lg border border-border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
              {inviteStatus}
            </div>
          )}

          {createdURL && (
            <div className="mt-4 rounded-lg border border-border bg-muted/30 p-3">
              <div className="text-xs font-medium text-muted-foreground mb-2">Link do convite</div>
              <div className="flex flex-col sm:flex-row gap-2">
                <Input value={createdURL} readOnly />
                <Button type="button" variant="outline" onClick={copyInvitationURL}>
                  <Copy className="mr-2 h-4 w-4" />
                  Copiar
                </Button>
              </div>
            </div>
          )}

          {error && (
            <div className="mt-3 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {error}
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid gap-6 lg:grid-cols-2">
        <AccessList title="Usuários ativos" emptyText="Nenhum usuário carregado." isLoading={isLoading}>
          {users.map((user) => (
            <div key={user.id} className="flex items-center justify-between gap-4 rounded-lg border border-border/60 bg-card p-4">
              <div className="min-w-0">
                <h3 className="font-medium truncate">{user.name}</h3>
                <p className="text-sm text-muted-foreground truncate">{user.email}</p>
              </div>
              <Badge variant="secondary">{roleLabels[user.role]}</Badge>
            </div>
          ))}
        </AccessList>

        <AccessList title="Convites" emptyText="Nenhum convite criado." isLoading={isLoading}>
          {invitations.map((invitation) => (
            <div key={invitation.id} className="rounded-lg border border-border/60 bg-card p-4 space-y-2">
              <div className="flex items-start justify-between gap-4">
                <div className="min-w-0">
                  <h3 className="font-medium truncate">{invitation.email}</h3>
                  <p className="text-sm text-muted-foreground truncate">
                    {invitation.client_name ? `Cliente: ${invitation.client_name}` : "Acesso da agência"}
                  </p>
                </div>
                <Badge variant={invitation.accepted_at ? "secondary" : "outline"}>
                  {invitation.accepted_at ? "Aceito" : roleLabels[invitation.role]}
                </Badge>
              </div>
              <p className="text-xs text-muted-foreground">
                Expira em {new Intl.DateTimeFormat("pt-BR", { dateStyle: "medium" }).format(new Date(invitation.expires_at))}
              </p>
            </div>
          ))}
        </AccessList>
      </div>
    </div>
  );
}

function AccessList({ title, emptyText, isLoading, children }: { title: string; emptyText: string; isLoading: boolean; children: ReactNode }) {
  const hasChildren = Array.isArray(children) ? children.length > 0 : Boolean(children);

  return (
    <div className="space-y-3">
      <h2 className="text-base font-semibold">{title}</h2>
      {isLoading && <p className="text-sm text-muted-foreground py-4">Carregando...</p>}
      {!isLoading && !hasChildren && (
        <div className="flex items-center justify-center h-[220px] border border-dashed border-border rounded-xl">
          <div className="text-center space-y-3">
            <div className="bg-muted w-12 h-12 rounded-full flex items-center justify-center mx-auto">
              <Users className="h-6 w-6 text-muted-foreground" />
            </div>
            <p className="text-sm text-muted-foreground w-[260px]">{emptyText}</p>
          </div>
        </div>
      )}
      {!isLoading && hasChildren && <div className="grid gap-3">{children}</div>}
    </div>
  );
}
