import { Head, Link, usePage } from '@inertiajs/react';
import {
    AlertCircle,
    CheckCircle2,
    Clock,
    Pause,
    Ticket,
    TrendingUp,
    Wrench,
} from 'lucide-react';
import { StatsCard } from '@/components/stats-card';
import { TicketPriorityBadge } from '@/components/ticket-priority-badge';
import { TicketStatusBadge } from '@/components/ticket-status-badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import type {
    BreadcrumbItem,
    DashboardStats,
    Ticket as TicketType,
    User,
    CategoryMap,
} from '@/types';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
];

const categoryLabels: Record<string, string> = {
    hardware_repair: 'Hardware Repair',
    software_issue: 'Software Issue',
    network: 'Network',
    printer: 'Printer',
    account_access: 'Account Access',
    other: 'Other',
};

const categoryColors: Record<string, string> = {
    hardware_repair: 'bg-orange-500',
    software_issue: 'bg-blue-500',
    network: 'bg-purple-500',
    printer: 'bg-teal-500',
    account_access: 'bg-amber-500',
    other: 'bg-gray-500',
};

type DashboardProps = {
    stats: DashboardStats;
    byCategory: Record<string, number>;
    recentTickets: TicketType[];
    myAssigned: TicketType[];
};

export default function Dashboard({ stats, byCategory, recentTickets, myAssigned }: DashboardProps) {
    const { auth } = usePage<{ auth: { user: User } }>().props;
    const isStaff = auth.user.role === 'admin' || auth.user.role === 'technician';

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Dashboard" />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                {/* Welcome Header */}
                <div className="flex flex-col gap-1">
                    <h1 className="text-2xl font-bold tracking-tight">
                        Welcome back, {auth.user.name}!
                    </h1>
                    <p className="text-muted-foreground">
                        {isStaff
                            ? "Here's an overview of all ICT support tickets."
                            : "Here's the status of your ICT support requests."}
                    </p>
                </div>

                {/* Stats Cards */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <StatsCard
                        title="Open Tickets"
                        value={stats.open}
                        icon={AlertCircle}
                        description="Awaiting assignment"
                    />
                    <StatsCard
                        title="In Progress"
                        value={stats.in_progress}
                        icon={Clock}
                        description="Being worked on"
                    />
                    <StatsCard
                        title="Resolved"
                        value={stats.resolved}
                        icon={CheckCircle2}
                        description="Successfully resolved"
                    />
                    {stats.critical > 0 && (
                        <StatsCard
                            title="Critical"
                            value={stats.critical}
                            icon={AlertCircle}
                            description="Needs immediate attention"
                            className="border-red-200 dark:border-red-900"
                            iconClassName="bg-red-100 dark:bg-red-900/30"
                        />
                    )}
                    {stats.critical === 0 && (
                        <StatsCard
                            title="Total Tickets"
                            value={stats.total}
                            icon={Ticket}
                            description="All time"
                        />
                    )}
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Recent Tickets */}
                    <Card className="lg:col-span-2">
                        <CardHeader className="flex flex-row items-center justify-between pb-2">
                            <div>
                                <CardTitle className="text-lg">Recent Tickets</CardTitle>
                                <CardDescription>Latest ICT support requests</CardDescription>
                            </div>
                            <Link
                                href="/tickets"
                                className="text-sm font-medium text-primary hover:underline"
                            >
                                View all →
                            </Link>
                        </CardHeader>
                        <CardContent>
                            <div className="space-y-3">
                                {recentTickets.length === 0 ? (
                                    <div className="flex flex-col items-center justify-center py-12 text-center">
                                        <Ticket className="mb-3 h-12 w-12 text-muted-foreground/30" />
                                        <p className="text-sm text-muted-foreground">No tickets yet</p>
                                        {auth.user.role !== 'admin' && (
                                            <Link
                                                href="/tickets/create"
                                                className="mt-2 text-sm font-medium text-primary hover:underline"
                                            >
                                                Create your first ticket
                                            </Link>
                                        )}
                                    </div>
                                ) : (
                                    recentTickets.slice(0, 7).map((ticket) => (
                                        <Link
                                            key={ticket.id}
                                            href={`/tickets/${ticket.id}`}
                                            className="group flex items-center gap-4 rounded-lg border border-transparent p-3 transition-all duration-200 hover:border-border hover:bg-accent/50 hover:shadow-sm"
                                        >
                                            <div className="flex-1 min-w-0">
                                                <div className="flex items-center gap-2 mb-1">
                                                    <span className="text-xs font-mono text-muted-foreground">
                                                        {ticket.ticket_number}
                                                    </span>
                                                </div>
                                                <p className="truncate text-sm font-medium group-hover:text-primary transition-colors">
                                                    {ticket.title}
                                                </p>
                                                <p className="text-xs text-muted-foreground mt-0.5">
                                                    by {ticket.requester?.name} · {new Date(ticket.created_at).toLocaleDateString()}
                                                </p>
                                            </div>
                                            <div className="flex items-center gap-2 shrink-0">
                                                <TicketPriorityBadge priority={ticket.priority} />
                                                <TicketStatusBadge status={ticket.status} />
                                            </div>
                                        </Link>
                                    ))
                                )}
                            </div>
                        </CardContent>
                    </Card>

                    {/* Category Breakdown */}
                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-lg">By Category</CardTitle>
                            <CardDescription>Ticket distribution</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="space-y-4">
                                {Object.entries(categoryLabels).map(([key, label]) => {
                                    const count = byCategory[key] || 0;
                                    const total = stats.total || 1;
                                    const percentage = Math.round((count / total) * 100);
                                    return (
                                        <div key={key} className="space-y-2">
                                            <div className="flex items-center justify-between text-sm">
                                                <span className="font-medium">{label}</span>
                                                <span className="text-muted-foreground">{count}</span>
                                            </div>
                                            <div className="h-2 w-full overflow-hidden rounded-full bg-secondary">
                                                <div
                                                    className={`h-full rounded-full transition-all duration-500 ${categoryColors[key]}`}
                                                    style={{ width: `${percentage}%` }}
                                                />
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Assigned to me - only for staff */}
                {isStaff && myAssigned.length > 0 && (
                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-lg flex items-center gap-2">
                                <Wrench className="h-5 w-5" />
                                Assigned to Me
                            </CardTitle>
                            <CardDescription>Tickets you're currently working on</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="space-y-3">
                                {myAssigned.map((ticket) => (
                                    <Link
                                        key={ticket.id}
                                        href={`/tickets/${ticket.id}`}
                                        className="group flex items-center gap-4 rounded-lg border border-transparent p-3 transition-all duration-200 hover:border-border hover:bg-accent/50"
                                    >
                                        <div className="flex-1 min-w-0">
                                            <div className="flex items-center gap-2 mb-1">
                                                <span className="text-xs font-mono text-muted-foreground">
                                                    {ticket.ticket_number}
                                                </span>
                                                <TicketPriorityBadge priority={ticket.priority} />
                                            </div>
                                            <p className="truncate text-sm font-medium">{ticket.title}</p>
                                            <p className="text-xs text-muted-foreground">
                                                from {ticket.requester?.name}
                                            </p>
                                        </div>
                                        <TicketStatusBadge status={ticket.status} />
                                    </Link>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                )}
            </div>
        </AppLayout>
    );
}
