import React, { useState, useMemo } from 'react';
import { Head, useForm, usePage, router } from '@inertiajs/react';
import {
    Search,
    Plus,
    Bell,
    UserPlus,
    Activity,
    ShieldCheck,
    User,
    ChevronDown,
    Users,
    Mail,
    Shield,
    Trash2,
} from 'lucide-react';

interface Log {
    id: number;
    description: string;
    created_at: string;
    user?: {
        name: string;
    };
}
interface UserType {
    id: number;
    name: string;
    email: string;
    role: string;
    created_at: string;
}

interface Props {
    logs: Log[];
    users: UserType[];
}

export default function ManageUsers({ logs, users = [] }: Props) {
    const { props } = usePage();
    const auth = props.auth as any;

    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        email: '',
        password: '',
        role: 'user',
    });

    const [logSearch, setLogSearch] = useState('');

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post('/admin/users', {
            onSuccess: () => reset('name', 'email', 'password'),
        });
    };

    const handleDeleteUser = (id: number) => {
        if (confirm('Apakah Anda yakin ingin menghapus user ini?')) {
            router.delete(`/admin/users/${id}`);
        }
    };

    const filteredLogs = useMemo(() => {
        if (!logSearch) return logs;
        const term = logSearch.toLowerCase();
        return logs.filter(
            (log) =>
                log.description.toLowerCase().includes(term) ||
                log.user?.name?.toLowerCase().includes(term),
        );
    }, [logs, logSearch]);

    return (
        <>
            <Head title="Manage Users - Scuto Legal" />

            <div className="flex min-h-screen flex-1 flex-col bg-slate-900/40 text-slate-200">
                {/* HEADER SEARCH BAR (Mirip halaman kontrak) */}
                <header className="sticky top-0 z-40 border-b border-slate-800/80 bg-slate-900/60 backdrop-blur-md">
                    <div className="flex items-center justify-between px-8 py-4">
                        <div className="max-w-md flex-1">
                            <div className="relative">
                                <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-slate-500" />
                                <input
                                    type="text"
                                    placeholder="Search activity logs..."
                                    value={logSearch}
                                    onChange={(e) =>
                                        setLogSearch(e.target.value)
                                    }
                                    className="w-full rounded-xl border border-slate-800 bg-slate-950/40 py-2 pr-4 pl-9 text-sm text-slate-200 placeholder-slate-500 transition-colors focus:border-blue-500/80 focus:bg-slate-950/80 focus:ring-1 focus:ring-blue-500/30 focus:outline-none"
                                />
                            </div>
                        </div>

                        <div className="flex items-center gap-4">
                            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-tr from-orange-600 to-amber-500 text-sm font-bold text-white shadow-md shadow-orange-950/40">
                                {auth?.user?.name
                                    ? auth.user.name[0].toUpperCase()
                                    : 'A'}
                            </div>
                        </div>
                    </div>
                </header>

                {/* MAIN CONTENT AREA */}
                <main className="flex-1 space-y-6 overflow-auto p-8">
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight text-white">
                            Manage Users
                        </h1>
                        <p className="mt-1 text-sm text-slate-400">
                            Manage system access levels and review audit trails
                            in real-time.
                        </p>
                    </div>

                    {/* TWO COLUMN GRID LAYOUT */}
                    <div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
                        {/* Kiri: Form Create User */}
                        <div className="h-fit rounded-xl border border-slate-800 bg-slate-900/30 p-6 shadow-xl backdrop-blur-sm lg:col-span-5">
                            <div className="mb-5 flex items-center gap-3 border-b border-slate-800/60 pb-4">
                                <div className="rounded-lg bg-orange-600/10 p-2 text-orange-400">
                                    <UserPlus className="h-5 w-5" />
                                </div>
                                <h2 className="text-lg font-semibold text-white">
                                    Create New User
                                </h2>
                            </div>

                            <form onSubmit={handleSubmit} className="space-y-4">
                                <div>
                                    <label className="mb-2 block text-xs font-semibold tracking-wider text-slate-400 uppercase">
                                        Full Name
                                    </label>
                                    <input
                                        type="text"
                                        value={data.name}
                                        onChange={(e) =>
                                            setData('name', e.target.value)
                                        }
                                        className="w-full rounded-xl border border-slate-800 bg-slate-950/40 px-4 py-2.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500/80 focus:bg-slate-950/80 focus:outline-none"
                                        placeholder="John Doe"
                                    />
                                    {errors.name && (
                                        <p className="mt-1 text-xs text-red-400">
                                            {errors.name}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="mb-2 block text-xs font-semibold tracking-wider text-slate-400 uppercase">
                                        Email Address
                                    </label>
                                    <input
                                        type="email"
                                        value={data.email}
                                        onChange={(e) =>
                                            setData('email', e.target.value)
                                        }
                                        className="w-full rounded-xl border border-slate-800 bg-slate-950/40 px-4 py-2.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500/80 focus:bg-slate-950/80 focus:outline-none"
                                        placeholder="demo@example.com"
                                    />
                                    {errors.email && (
                                        <p className="mt-1 text-xs text-red-400">
                                            {errors.email}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="mb-2 block text-xs font-semibold tracking-wider text-slate-400 uppercase">
                                        Password
                                    </label>
                                    <input
                                        type="password"
                                        value={data.password}
                                        onChange={(e) =>
                                            setData('password', e.target.value)
                                        }
                                        className="w-full rounded-xl border border-slate-800 bg-slate-950/40 px-4 py-2.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500/80 focus:bg-slate-950/80 focus:outline-none"
                                        placeholder="••••••••"
                                    />
                                    {errors.password && (
                                        <p className="mt-1 text-xs text-red-400">
                                            {errors.password}
                                        </p>
                                    )}
                                </div>

                                <button
                                    type="submit"
                                    disabled={processing}
                                    className="mt-2 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-orange-600 px-4 py-2.5 text-sm font-semibold text-white shadow-md shadow-orange-900/20 transition-all hover:bg-orange-500 active:scale-[0.98] disabled:opacity-50"
                                >
                                    <Plus className="h-4 w-4" />
                                    {processing ? 'Creating...' : 'Create User'}
                                </button>
                            </form>
                        </div>

                        {/* Kanan: System Activity Logs & Registered Users */}
                        <div className="flex flex-col space-y-6 lg:col-span-7">
                            {/* Logs Box */}
                            <div className="rounded-xl border border-slate-800 bg-slate-900/30 p-6 shadow-xl backdrop-blur-sm">
                                <div className="mb-4 flex items-center justify-between border-b border-slate-800/60 pb-4">
                                    <div className="flex items-center gap-3">
                                        <div className="rounded-lg bg-orange-600/10 p-2 text-orange-400">
                                            <Activity className="h-5 w-5" />
                                        </div>
                                        <h2 className="text-lg font-semibold text-white">
                                            System Activity Logs
                                        </h2>
                                    </div>
                                    <span className="text-xs font-medium text-slate-500">
                                        Showing {filteredLogs.length} logs
                                    </span>
                                </div>

                                <div className="custom-scrollbar max-h-[300px] space-y-3 overflow-y-auto pr-2">
                                    {filteredLogs.length === 0 ? (
                                        <div className="flex flex-col items-center justify-center py-12 text-center">
                                            <Activity className="mb-2 h-8 w-8 animate-pulse text-slate-700" />
                                            <p className="text-sm text-slate-500 italic">
                                                No activity logs found.
                                            </p>
                                        </div>
                                    ) : (
                                        filteredLogs.map((log) => (
                                            <div
                                                key={log.id}
                                                className="flex items-start gap-3 rounded-xl border border-slate-800/40 bg-slate-950/20 p-3.5 transition-all hover:bg-slate-950/40"
                                            >
                                                <div className="mt-0.5 rounded-lg border border-slate-800/60 bg-slate-900/80 p-2 text-slate-400">
                                                    {log.description
                                                        .toLowerCase()
                                                        .includes('admin') ? (
                                                        <ShieldCheck className="h-4 w-4 text-emerald-400" />
                                                    ) : (
                                                        <User className="h-4 w-4 text-sky-400" />
                                                    )}
                                                </div>
                                                <div className="flex-1 space-y-1">
                                                    <p className="text-sm leading-relaxed text-slate-300">
                                                        <span className="font-semibold text-slate-100">
                                                            {log.user?.name ||
                                                                'System'}
                                                        </span>{' '}
                                                        {log.description}
                                                    </p>
                                                    <p className="text-xs font-medium text-slate-500">
                                                        {new Date(
                                                            log.created_at,
                                                        ).toLocaleString(
                                                            'id-ID',
                                                            {
                                                                dateStyle:
                                                                    'medium',
                                                                timeStyle:
                                                                    'short',
                                                            },
                                                        )}
                                                    </p>
                                                </div>
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>

                            {/* Registered Users Table Box */}
                            <div className="rounded-xl border border-slate-800 bg-slate-900/30 p-6 shadow-xl backdrop-blur-sm">
                                <div className="mb-4 flex items-center gap-3 border-b border-slate-800/60 pb-4">
                                    <div className="rounded-lg bg-orange-600/10 p-2 text-orange-400">
                                        <Users className="h-5 w-5" />
                                    </div>
                                    <div>
                                        <h2 className="text-base font-semibold text-white">
                                            Registered Users
                                        </h2>
                                        <p className="mt-0.5 text-xs text-slate-400">
                                            List of all accounts currently
                                            granted database access.
                                        </p>
                                    </div>
                                </div>

                                <div className="overflow-x-auto">
                                    <table className="w-full border-collapse text-left text-sm text-slate-300">
                                        <thead>
                                            <tr className="border-b border-slate-800 text-xs font-semibold tracking-wider text-slate-400 uppercase">
                                                <th className="px-4 py-3">
                                                    User
                                                </th>
                                                <th className="px-4 py-3">
                                                    Email
                                                </th>
                                                <th className="px-4 py-3">
                                                    Role
                                                </th>
                                                <th className="px-4 py-3">
                                                    Registered Date
                                                </th>
                                                <th className="px-4 py-3 text-right">
                                                    Actions
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-slate-800/40">
                                            {users.length === 0 ? (
                                                <tr>
                                                    <td
                                                        colSpan={5}
                                                        className="py-8 text-center text-sm text-slate-500 italic"
                                                    >
                                                        No registered users
                                                        found.
                                                    </td>
                                                </tr>
                                            ) : (
                                                users.map((u) => (
                                                    <tr
                                                        key={u.id}
                                                        className="transition-colors hover:bg-slate-950/20"
                                                    >
                                                        <td className="flex items-center gap-2 px-4 py-3.5 font-medium text-slate-200">
                                                            <div className="flex h-7 w-7 items-center justify-center rounded-full border border-slate-700 bg-slate-800 text-xs font-bold text-orange-400">
                                                                {u.name
                                                                    ? u.name[0].toUpperCase()
                                                                    : 'U'}
                                                            </div>
                                                            {u.name}
                                                        </td>
                                                        <td className="px-4 py-3.5 text-slate-400">
                                                            <span className="flex items-center gap-1.5">
                                                                <Mail className="h-3.5 w-3.5 text-slate-600" />
                                                                {u.email}
                                                            </span>
                                                        </td>
                                                        <td className="px-4 py-3.5">
                                                            {u.role ===
                                                            'admin' ? (
                                                                <span className="inline-flex items-center gap-1 rounded-md border border-emerald-500/20 bg-emerald-500/10 px-2 py-0.5 text-xs font-medium text-emerald-400">
                                                                    <Shield className="h-3 w-3" />{' '}
                                                                    Admin
                                                                </span>
                                                            ) : (
                                                                <span className="inline-flex items-center gap-1 rounded-md border border-sky-500/20 bg-sky-500/10 px-2 py-0.5 text-xs font-medium text-sky-400">
                                                                    <User className="h-3 w-3" />{' '}
                                                                    User
                                                                </span>
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-3.5 text-xs text-slate-500">
                                                            {new Date(
                                                                u.created_at,
                                                            ).toLocaleDateString(
                                                                'id-ID',
                                                                {
                                                                    dateStyle:
                                                                        'medium',
                                                                },
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-3.5 text-right">
                                                            {auth?.user?.id !==
                                                                u.id && (
                                                                <button
                                                                    onClick={() =>
                                                                        handleDeleteUser(
                                                                            u.id,
                                                                        )
                                                                    }
                                                                    className="rounded-lg p-1.5 text-slate-500 transition-colors hover:bg-red-500/10 hover:text-red-400"
                                                                    title="Delete User"
                                                                >
                                                                    <Trash2 className="h-4 w-4" />
                                                                </button>
                                                            )}
                                                        </td>
                                                    </tr>
                                                ))
                                            )}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </main>
            </div>
        </>
    );
}
