import { router } from '@inertiajs/react';
import {
    PlusCircle,
    CheckCircle2,
    CalendarRange,
    MessageSquare,
    UserPlus,
    ArrowRightLeft,
    Activity,
    Clock,
} from 'lucide-react';
import type { ProjectInfoData } from '@/types/project';

interface ProjectInfoProps {
    project: ProjectInfoData;
}

const STATUS_CONFIG: Record<
    string,
    { label: string; color: string; dot: string }
> = {
    active: {
        label: 'Active',
        color: 'text-sky-600 dark:text-sky-400',
        dot: 'bg-sky-500 shadow-[0_0_8px_rgba(14,165,233,0.4)]',
    },
    in_progress: {
        label: 'In Progress',
        color: 'text-blue-600 dark:text-blue-400',
        dot: 'bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.4)]',
    },
    completed: {
        label: 'Completed',
        color: 'text-emerald-600 dark:text-emerald-400',
        dot: 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.4)]',
    },
    done: {
        label: 'Completed',
        color: 'text-emerald-600 dark:text-emerald-400',
        dot: 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.4)]',
    },
    pending: {
        label: 'Pending',
        color: 'text-amber-600 dark:text-amber-400',
        dot: 'bg-amber-500 shadow-[0_0_8px_rgba(245,158,11,0.4)]',
    },
    on_hold: {
        label: 'On Hold',
        color: 'text-orange-600 dark:text-orange-400',
        dot: 'bg-orange-500 shadow-[0_0_8px_rgba(249,115,22,0.4)]',
    },
    cancelled: {
        label: 'Cancelled',
        color: 'text-rose-600 dark:text-rose-400',
        dot: 'bg-rose-500 shadow-[0_0_8px_rgba(244,63,94,0.4)]',
    },
    archived: {
        label: 'Archived',
        color: 'text-slate-600 dark:text-slate-400',
        dot: 'bg-slate-500 shadow-none',
    },
    inactive: {
        label: 'Inactive',
        color: 'text-slate-600 dark:text-slate-400',
        dot: 'bg-slate-500 shadow-none',
    },
    draft: {
        label: 'Draft',
        color: 'text-slate-500 dark:text-slate-400',
        dot: 'bg-slate-500 shadow-none',
    },
    todo: {
        label: 'To Do',
        color: 'text-purple-600 dark:text-purple-400',
        dot: 'bg-purple-500 shadow-[0_0_8px_rgba(168,85,247,0.4)]',
    },
};

export function ProjectInfo({ project }: ProjectInfoProps) {
    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('id-ID', {
            day: 'numeric',
            month: 'long',
            year: 'numeric',
        });
    };

    const formatActivityTime = (dateString: string) => {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMin = Math.floor(diffMs / 60000);
        const diffHrs = Math.floor(diffMin / 60);
        const diffDays = Math.floor(diffHrs / 24);

        if (diffMin < 1) {
            return 'Baru saja';
        }

        if (diffMin < 60) {
            return `${diffMin} menit lalu`;
        }

        if (diffHrs < 24) {
            return `${diffHrs} jam lalu`;
        }

        if (diffDays === 1) {
            return 'Kemarin';
        }

        if (diffDays < 7) {
            return `${diffDays} hari lalu`;
        }

        return date
            .toLocaleDateString('id-ID', {
                day: 'numeric',
                month: 'short',
                hour: '2-digit',
                minute: '2-digit',
            })
            .replace(/\./g, ':');
    };

    const getActivityConfig = (type: string) => {
        switch (type) {
            case 'project_status_updated':
                return {
                    icon: <ArrowRightLeft className="h-4 w-4 text-sky-500" />,
                    bgColor:
                        'bg-sky-50 dark:bg-sky-950/30 border-sky-100 dark:border-sky-900/50',
                };
            case 'task_created':
                return {
                    icon: <PlusCircle className="h-4 w-4 text-emerald-500" />,
                    bgColor:
                        'bg-emerald-50 dark:bg-emerald-950/30 border-emerald-100 dark:border-emerald-900/50',
                };
            case 'task_status_updated':
                return {
                    icon: <CheckCircle2 className="h-4 w-4 text-indigo-500" />,
                    bgColor:
                        'bg-indigo-50 dark:bg-indigo-950/30 border-indigo-100 dark:border-indigo-900/50',
                };
            case 'task_due_date_updated':
                return {
                    icon: <CalendarRange className="h-4 w-4 text-amber-500" />,
                    bgColor:
                        'bg-amber-50 dark:bg-amber-950/30 border-amber-100 dark:border-amber-900/50',
                };
            case 'comment_added':
                return {
                    icon: <MessageSquare className="h-4 w-4 text-sky-500" />,
                    bgColor:
                        'bg-sky-50 dark:bg-sky-950/30 border-sky-100 dark:border-sky-900/50',
                };
            case 'member_joined':
                return {
                    icon: <UserPlus className="h-4 w-4 text-violet-500" />,
                    bgColor:
                        'bg-violet-50 dark:bg-violet-950/30 border-violet-100 dark:border-violet-900/50',
                };
            case 'member_role_updated':
                return {
                    icon: <ArrowRightLeft className="h-4 w-4 text-blue-500" />,
                    bgColor:
                        'bg-blue-50 dark:bg-blue-950/30 border-blue-100 dark:border-blue-900/50',
                };
            case 'member_removed':
                return {
                    icon: <Activity className="h-4 w-4 text-rose-500" />,
                    bgColor:
                        'bg-rose-50 dark:bg-rose-950/30 border-rose-100 dark:border-rose-900/50',
                };
            default:
                return {
                    icon: (
                        <Activity className="h-4 w-4 text-muted-foreground" />
                    ),
                    bgColor: 'bg-muted border-border',
                };
        }
    };

    const activitiesPaginated = project.activities;
    const activities = activitiesPaginated?.data || [];

    const handlePageChange = (url: string) => {
        router.get(
            url,
            {},
            {
                preserveScroll: true,
                preserveState: true,
            },
        );
    };

    const statusKey = (project.progressStatus || '').toLowerCase();
    const statusConfig = STATUS_CONFIG[statusKey] || {
        label: project.progressStatus || '-',
        color: 'text-foreground',
        dot: 'bg-muted-foreground shadow-none',
    };

    return (
        <div className="space-y-6">
            {/* Project Metadata Section */}
            <section className="rounded-xl border bg-card p-6 shadow-xs">
                <h2 className="mb-6 text-lg font-bold">Project Information</h2>
                <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                    <div className="space-y-1.5">
                        <span className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                            Deadline
                        </span>
                        <div className="flex items-center gap-2 text-sm font-medium text-foreground">
                            <CalendarRange className="h-4 w-4 text-muted-foreground" />
                            {formatDate(project.deadline)}
                        </div>
                    </div>
                    <div className="space-y-1.5">
                        <span className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                            Project Status
                        </span>
                        <div className="flex items-center gap-2">
                            <div
                                className={`h-2 w-2 animate-pulse rounded-full ${statusConfig.dot}`}
                            />
                            <span
                                className={`text-sm font-semibold ${statusConfig.color}`}
                            >
                                {statusConfig.label}
                            </span>
                        </div>
                    </div>
                    {project.overviews && (
                        <div className="mt-2 space-y-1.5 border-t pt-4 md:col-span-2">
                            <span className="text-xs font-semibold tracking-wider text-muted-foreground uppercase">
                                Overview
                            </span>
                            <p className="text-sm leading-relaxed whitespace-pre-line text-muted-foreground">
                                {project.overviews}
                            </p>
                        </div>
                    )}
                </div>
            </section>

            {/* Project Activities Section */}
            <section className="rounded-xl border bg-card p-6 shadow-xs">
                <div className="mb-6 flex items-center justify-between">
                    <h2 className="flex items-center gap-2 text-lg font-bold">
                        <Activity className="h-4 w-4 text-primary" />
                        Aktivitas Proyek
                    </h2>
                    <span className="rounded-full bg-muted px-2.5 py-0.5 text-xs font-medium text-muted-foreground">
                        {activitiesPaginated?.total || 0} Aktivitas
                    </span>
                </div>

                {activities.length === 0 ? (
                    <div className="flex flex-col items-center justify-center rounded-xl border border-dashed bg-muted/30 py-10 text-center">
                        <Activity className="mb-2 h-8 w-8 stroke-[1.5] text-muted-foreground/40" />
                        <p className="text-sm font-medium text-muted-foreground">
                            Belum ada rekaman aktivitas
                        </p>
                        <p className="mt-1 text-xs text-muted-foreground/60">
                            Segala pembaruan tugas dan kolaborasi akan terekam
                            secara otomatis di sini.
                        </p>
                    </div>
                ) : (
                    <div className="relative space-y-6 pb-2 pl-4 before:absolute before:top-3 before:bottom-3 before:left-5.75 before:w-0.5 before:bg-muted dark:before:bg-neutral-800">
                        {activities.map((activity) => {
                            const config = getActivityConfig(
                                activity.activity_type,
                            );

                            return (
                                <div
                                    key={activity.id}
                                    className="group relative flex gap-4"
                                >
                                    {/* Timeline Indicator */}
                                    <div
                                        className={`relative z-10 flex h-9 w-9 shrink-0 items-center justify-center rounded-full border-2 border-background ${config.bgColor} shadow-sm transition-transform duration-200 group-hover:scale-110`}
                                    >
                                        {config.icon}
                                    </div>

                                    {/* Activity Content */}
                                    <div className="flex-1 pt-1.5">
                                        <div className="flex flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between">
                                            <p className="text-sm leading-snug font-medium text-foreground">
                                                <span className="font-mono text-[13px] font-semibold text-primary">
                                                    @{activity.user.name}
                                                </span>
                                                <span className="font-normal text-muted-foreground">
                                                    {' '}
                                                </span>
                                                {activity.description}
                                            </p>
                                            <span className="flex shrink-0 items-center gap-1 text-[11px] font-medium whitespace-nowrap text-muted-foreground">
                                                <Clock className="h-3 w-3" />
                                                {formatActivityTime(
                                                    activity.created_at,
                                                )}
                                            </span>
                                        </div>

                                        {/* Dynamic Meta Badges/Chips if needed based on metadata */}
                                        {activity.properties &&
                                            (activity.properties.task_code ||
                                                activity.properties.role) && (
                                                <div className="mt-1.5 flex flex-wrap gap-1.5">
                                                    {activity.properties
                                                        .task_code && (
                                                        <span className="inline-flex items-center rounded border bg-muted px-2 py-0.5 font-mono text-[10px] font-medium text-muted-foreground">
                                                            {
                                                                activity
                                                                    .properties
                                                                    .task_code
                                                            }
                                                        </span>
                                                    )}
                                                    {activity.properties
                                                        .role && (
                                                        <span className="inline-flex items-center rounded bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary capitalize">
                                                            {activity.properties.role.replace(
                                                                '-',
                                                                ' ',
                                                            )}
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}

                {/* Activities Pagination Controls */}
                {activitiesPaginated && activitiesPaginated.last_page > 1 && (
                    <div className="mt-6 flex flex-col gap-4 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
                        <span className="text-center text-xs text-muted-foreground sm:text-left">
                            Menampilkan {activities.length} dari{' '}
                            {activitiesPaginated.total} aktivitas
                        </span>
                        <div className="flex items-center justify-center gap-1.5">
                            <button
                                type="button"
                                disabled={!activitiesPaginated.prev_page_url}
                                onClick={() =>
                                    activitiesPaginated.prev_page_url &&
                                    handlePageChange(
                                        activitiesPaginated.prev_page_url,
                                    )
                                }
                                className="cursor-pointer rounded-md border border-border bg-card px-2.5 py-1.5 text-xs font-semibold text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-card"
                            >
                                Kembali
                            </button>
                            <div className="px-2 text-xs font-medium text-foreground">
                                Halaman {activitiesPaginated.current_page} /{' '}
                                {activitiesPaginated.last_page}
                            </div>
                            <button
                                type="button"
                                disabled={!activitiesPaginated.next_page_url}
                                onClick={() =>
                                    activitiesPaginated.next_page_url &&
                                    handlePageChange(
                                        activitiesPaginated.next_page_url,
                                    )
                                }
                                className="cursor-pointer rounded-md border border-border bg-card px-2.5 py-1.5 text-xs font-semibold text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-card"
                            >
                                Lanjut
                            </button>
                        </div>
                    </div>
                )}
            </section>
        </div>
    );
}
