import { useMemo, useEffect } from "react";
import AppLayout from "@/Layouts/AppLayout";
import { Head, Link, useForm, router, usePage } from "@inertiajs/react";
import { toast } from "sonner";
import {
    Users,
    Trash2,
    Save,
    User,
    Key,
    Check,
    X,
} from "lucide-react";
import { cn } from "@/lib/utils";
import PageHeader from "@/Components/PageHeader";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { MultiSelect } from "@/Components/ui/multi-select";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/Components/ui/card";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";

export default function Form({ user, projects = [], groups = [] }) {
    const { flash } = usePage().props;
    const isEditing = !!user;

    useEffect(() => {
        if (flash?.success) toast.success(flash.success);
        if (flash?.error) toast.error(flash.error);
    }, [flash?.success, flash?.error]);

    const { data, setData, post, put, processing, errors } = useForm({
        name: user?.name ?? "",
        email: user?.email ?? "",
        password: "",
        password_confirmation: "",
        status: user?.status ?? "active",
        group_ids:   user?.group_ids   ?? [],
        project_ids: user?.project_ids ?? [],
    });

    const passwordChecks = useMemo(
        () => checkPasswordRules(data.password),
        [data.password]
    );
    const passwordValid = Object.values(passwordChecks).every(Boolean);
    const passwordsMatch =
        data.password.length === 0 ||
        data.password === data.password_confirmation;
    const passwordOk =
        data.password.length === 0 || (passwordValid && passwordsMatch);

    // Cobertura dinâmica pelos grupos selecionados
    const coveredByGroups = new Set(
        data.group_ids.flatMap(
            (gid) => groups.find((g) => g.id === gid)?.project_ids ?? []
        )
    );

    const groupOptions = groups.map((g) => ({
        value: g.id,
        label: g.name,
        hint: `${g.project_ids?.length ?? 0} projeto(s)`,
    }));

    const projectOptions = projects.map((p) => {
        const covered = coveredByGroups.has(p.id);
        return {
            value: p.id,
            label: p.name,
            disabled: covered,
            hint: covered ? "via grupo" : undefined,
        };
    });

    const projectSelectValue = [
        ...coveredByGroups,
        ...data.project_ids.filter((p) => !coveredByGroups.has(p)),
    ];

    function onProjectsChange(next) {
        setData(
            "project_ids",
            next.filter((p) => !coveredByGroups.has(p))
        );
    }

    function handleSubmit(e) {
        e?.preventDefault();
        if (!passwordOk) return;

        if (isEditing) {
            put(route("usuarios.update", user.id));
        } else {
            post(route("usuarios.store"));
        }
    }

    function destroyUser() {
        router.delete(route("usuarios.destroy", user.id));
    }

    const totalProjects =
        coveredByGroups.size + data.project_ids.length;

    // Faixa de identidade (logo abaixo do PageHeader, antes dos cards)
    const identityName =
        data.name.trim() || (isEditing ? user.name : "Sem nome definido");
    const identitySubline = isEditing
        ? `${data.email || user.email} · acesso a ${totalProjects} projeto${totalProjects === 1 ? "" : "s"}`
        : data.email.trim()
            ? data.email
            : "Preencha os dados abaixo para criar o usuário";

    const submitDisabled = processing || !passwordOk;

    return (
        <AppLayout>
            <Head title={isEditing ? "Editar usuário" : "Novo usuário"} />

            <div className="mx-auto w-full max-w-[680px] flex flex-col gap-4">
                <PageHeader
                    title={isEditing ? "Editar usuário" : "Novo usuário"}
                    breadcrumb={[{ label: "Usuários", href: "usuarios.index", icon: Users }]}
                />

                {/* Faixa de identidade */}
                <div className="flex items-center gap-3 pb-1">
                    <UserAvatar name={data.name} />
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center min-w-0">
                            <p className="text-base font-medium truncate">{identityName}</p>
                            <StatusPill status={data.status} className="ml-2" />
                        </div>
                        <p className="text-sm text-muted-foreground mt-0.5 truncate">
                            {identitySubline}
                        </p>
                    </div>
                </div>

                <form onSubmit={handleSubmit} className="space-y-[18px]">
                    {/* Card 1 - Identidade */}
                    <SectionCard title="Identidade">
                        <Field
                            label="Nome"
                            htmlFor="name"
                            error={errors.name}
                        >
                            <Input
                                id="name"
                                value={data.name}
                                onChange={(e) => setData("name", e.target.value)}
                                className="h-9"
                            />
                        </Field>

                        <Field
                            label="Email"
                            htmlFor="email"
                            hint="O usuário também pode entrar por Google com este e-mail."
                            error={errors.email}
                        >
                            <Input
                                id="email"
                                type="email"
                                value={data.email}
                                onChange={(e) => setData("email", e.target.value)}
                                className="h-9"
                            />
                        </Field>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <Field label="Status">
                                <Select
                                    value={data.status}
                                    onValueChange={(v) => setData("status", v)}
                                >
                                    <SelectTrigger className="h-9">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="active">Ativo</SelectItem>
                                        <SelectItem value="inactive">Inativo</SelectItem>
                                        {data.status === "blocked" && (
                                            <SelectItem value="blocked">
                                                Bloqueado
                                            </SelectItem>
                                        )}
                                    </SelectContent>
                                </Select>
                            </Field>

                            {isEditing && (
                                <Field label="Login Google">
                                    <GoogleIndicator connected={!!user?.has_google} />
                                </Field>
                            )}
                        </div>
                    </SectionCard>

                    {/* Card 2 - Segurança */}
                    <SectionCard
                        title={isEditing ? "Segurança" : "Senha"}
                        subtitle={
                            isEditing
                                ? "Deixe em branco para manter a senha atual."
                                : "O usuário também pode entrar por Google e definir a senha depois."
                        }
                    >
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <Field
                                label={isEditing ? "Nova senha" : "Senha"}
                                htmlFor="password"
                                error={errors.password}
                            >
                                <PasswordInput
                                    id="password"
                                    value={data.password}
                                    placeholder={isEditing ? "••••••••" : "Opcional"}
                                    onChange={(e) =>
                                        setData("password", e.target.value)
                                    }
                                />
                            </Field>

                            <Field
                                label="Confirmar"
                                htmlFor="password_confirmation"
                                error={
                                    data.password_confirmation.length > 0 &&
                                    !passwordsMatch
                                        ? "As senhas não conferem."
                                        : undefined
                                }
                            >
                                <PasswordInput
                                    id="password_confirmation"
                                    value={data.password_confirmation}
                                    placeholder="••••••••"
                                    onChange={(e) =>
                                        setData(
                                            "password_confirmation",
                                            e.target.value
                                        )
                                    }
                                />
                            </Field>
                        </div>

                        {data.password.length > 0 && (
                            <PasswordStrength checks={passwordChecks} />
                        )}
                    </SectionCard>

                    {/* Card 3 - Acesso a projetos */}
                    <SectionCard
                        title="Acesso a projetos"
                        subtitle="Selecione grupos ou projetos individuais."
                    >
                        {groups.length > 0 && (
                            <Field label="Grupos">
                                <MultiSelect
                                    options={groupOptions}
                                    value={data.group_ids}
                                    onChange={(next) => setData("group_ids", next)}
                                    placeholder="Selecionar grupos..."
                                    searchPlaceholder="Buscar grupo..."
                                    emptyText="Nenhum grupo encontrado."
                                />
                            </Field>
                        )}

                        <Field label="Projetos">
                            {projects.length === 0 ? (
                                <p className="text-xs text-muted-foreground">
                                    Nenhum projeto cadastrado no sistema.
                                </p>
                            ) : (
                                <MultiSelect
                                    options={projectOptions}
                                    value={projectSelectValue}
                                    onChange={onProjectsChange}
                                    placeholder={
                                        isEditing
                                            ? "Selecionar projetos..."
                                            : "Nenhum projeto adicionado"
                                    }
                                    searchPlaceholder="Buscar projeto..."
                                    emptyText="Nenhum projeto encontrado."
                                />
                            )}
                        </Field>
                    </SectionCard>

                    {/* Footer */}
                    <div className="flex items-center justify-between gap-2 pt-1">
                        <div>
                            {isEditing && (
                                <AlertDialog>
                                    <AlertDialogTrigger asChild>
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            className="h-9 text-destructive hover:text-destructive hover:bg-destructive/10"
                                        >
                                            <Trash2 className="h-4 w-4" />
                                            Remover usuário
                                        </Button>
                                    </AlertDialogTrigger>
                                    <AlertDialogContent>
                                        <AlertDialogHeader>
                                            <AlertDialogTitle>Remover usuário?</AlertDialogTitle>
                                            <AlertDialogDescription>
                                                Esta ação é irreversível. O usuário perderá o acesso e todos os vínculos com projetos serão removidos.
                                            </AlertDialogDescription>
                                        </AlertDialogHeader>
                                        <AlertDialogFooter>
                                            <AlertDialogCancel>Cancelar</AlertDialogCancel>
                                            <AlertDialogAction onClick={destroyUser}>
                                                Remover
                                            </AlertDialogAction>
                                        </AlertDialogFooter>
                                    </AlertDialogContent>
                                </AlertDialog>
                            )}
                        </div>
                        <div className="flex items-center gap-2">
                            <Button type="button" variant="ghost" asChild>
                                <Link href={route("usuarios.index")}>Cancelar</Link>
                            </Button>
                            <Button type="submit" disabled={submitDisabled} className="h-9">
                                <Save className="h-4 w-4" />
                                {processing
                                    ? "Salvando..."
                                    : isEditing
                                        ? "Salvar alterações"
                                        : "Criar usuário"}
                            </Button>
                        </div>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}

// ── Sub-componentes ─────────────────────────────────────────────────────────

function SectionCard({ title, subtitle, action, children }) {
    return (
        <Card>
            <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
                <div className="min-w-0">
                    <CardTitle>{title}</CardTitle>
                    {subtitle && <CardDescription>{subtitle}</CardDescription>}
                </div>
                {action}
            </CardHeader>
            <CardContent className="space-y-3">{children}</CardContent>
        </Card>
    );
}

function Field({ label, hint, error, htmlFor, children }) {
    return (
        <div className="space-y-1.5">
            <Label htmlFor={htmlFor} className="text-sm font-medium">
                {label}
            </Label>
            {children}
            {error ? (
                <p className="text-xs text-red-500">{error}</p>
            ) : hint ? (
                <p className="text-xs text-muted-foreground">{hint}</p>
            ) : null}
        </div>
    );
}

function PasswordInput({ id, value, onChange, placeholder }) {
    return (
        <div className="relative">
            <Key className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none" />
            <Input
                id={id}
                type="password"
                value={value}
                onChange={onChange}
                placeholder={placeholder}
                autoComplete="new-password"
                className="h-9 pl-8"
            />
        </div>
    );
}

function UserAvatar({ name }) {
    const initials = computeInitials(name);
    const showInitials = initials.length > 0;

    return (
        <div
            className={cn(
                "h-14 w-14 rounded-full flex items-center justify-center shrink-0",
                showInitials
                    ? "bg-brand text-white"
                    : "bg-muted text-muted-foreground"
            )}
        >
            {showInitials ? (
                <span className="text-[20px] font-semibold tracking-tight">
                    {initials}
                </span>
            ) : (
                <User className="h-7 w-7" />
            )}
        </div>
    );
}

function StatusPill({ status, className }) {
    const label =
        status === "active"
            ? "Ativo"
            : status === "blocked"
                ? "Bloqueado"
                : "Inativo";
    const isActive = status === "active";
    const isBlocked = status === "blocked";

    return (
        <span
            className={cn(
                "inline-flex items-center gap-[5px] rounded-full text-[11px] py-0.5 pl-[7px] pr-2",
                isActive &&
                    "bg-emerald-500/10 border border-emerald-500/30 text-emerald-500",
                isBlocked &&
                    "bg-red-500/10 border border-red-500/30 text-red-500",
                !isActive &&
                    !isBlocked &&
                    "bg-white/5 border border-border text-muted-foreground",
                className
            )}
        >
            <span
                className={cn(
                    "h-1.5 w-1.5 rounded-full",
                    isActive && "bg-emerald-500",
                    isBlocked && "bg-red-500",
                    !isActive && !isBlocked && "bg-muted-foreground/60"
                )}
            />
            {label}
        </span>
    );
}

function GoogleIndicator({ connected }) {
    return (
        <div className="flex h-9 items-center gap-2 rounded-md border border-input bg-muted/30 px-2.5 text-sm">
            <GoogleIcon className="h-3.5 w-3.5" />
            <span
                className={cn(
                    connected ? "text-foreground" : "text-muted-foreground"
                )}
            >
                {connected ? "Conectado" : "Não conectado"}
            </span>
        </div>
    );
}

function GoogleIcon({ className }) {
    return (
        <svg className={className} viewBox="0 0 24 24">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4" />
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
        </svg>
    );
}

function computeInitials(name) {
    if (!name) return "";
    const parts = name.trim().split(/\s+/).filter(Boolean);
    if (parts.length === 0) return "";
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function checkPasswordRules(password) {
    return {
        length: password.length >= 8,
        lower: /[a-z]/.test(password),
        upper: /[A-Z]/.test(password),
        number: /[0-9]/.test(password),
        symbol: /[^A-Za-z0-9]/.test(password),
    };
}

const RULE_LABELS = {
    length: "8+ caracteres",
    lower: "letra minúscula",
    upper: "letra maiúscula",
    number: "número",
    symbol: "símbolo",
};

function PasswordStrength({ checks }) {
    const passed = Object.values(checks).filter(Boolean).length;
    const total = Object.keys(checks).length;
    const pct = (passed / total) * 100;
    const color =
        passed <= 2
            ? "bg-destructive"
            : passed <= 4
                ? "bg-amber-500"
                : "bg-emerald-500";

    return (
        <div className="space-y-1.5">
            <div className="h-1 w-full rounded-full bg-muted overflow-hidden">
                <div
                    className={`h-full transition-all ${color}`}
                    style={{ width: `${pct}%` }}
                />
            </div>
            <ul className="grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px]">
                {Object.entries(checks).map(([key, ok]) => (
                    <li
                        key={key}
                        className={`flex items-center gap-1 ${ok ? "text-emerald-600 dark:text-emerald-400" : "text-muted-foreground"}`}
                    >
                        {ok ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}
                        {RULE_LABELS[key]}
                    </li>
                ))}
            </ul>
        </div>
    );
}
