"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { AppointmentForm } from "@/modules/appointments/appointment-form"
import { AppointmentsCalendarView } from "@/modules/appointments/appointments-calendar-view"
import { APPOINTMENT_ROUTES, AppointmentStatus } from "@garage/api"
import type { AppointmentsClient } from "@garage/api"
import { CalendarCheck2Icon, CalendarDaysIcon, ClipboardListIcon, ClockIcon, ListIcon } from "lucide-react"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { RelationLink } from "@/shared/components/relation-link"
import { formatEnum } from "@/shared/utils/formatters"

const STATUS_COLORS: Record<string, string> = {
    requested: "bg-yellow-100 text-yellow-800",
    confirmed: "bg-blue-100 text-blue-800",
    in_progress: "bg-purple-100 text-purple-800",
    completed: "bg-green-100 text-green-800",
    cancelled: "bg-red-100 text-red-800",
}

export default function AppointmentsPage() {
    const router = useRouter()
    const [view, setView] = useState<"list" | "calendar">("list")

    const viewToggle = (
        <div className="flex items-center justify-end gap-1 px-1">
            <Button
                type="button"
                variant={view === "list" ? "default" : "outline"}
                size="sm"
                onClick={() => setView("list")}
            >
                <ListIcon className="me-1 size-4" /> List
            </Button>
            <Button
                type="button"
                variant={view === "calendar" ? "default" : "outline"}
                size="sm"
                onClick={() => setView("calendar")}
            >
                <CalendarDaysIcon className="me-1 size-4" /> Calendar
            </Button>
        </div>
    )

    if (view === "calendar") {
        return (
            <div className="space-y-4 p-4">
                <div className="flex items-center justify-between">
                    <h1 className="text-xl font-semibold">Appointments</h1>
                    {viewToggle}
                </div>
                <AppointmentsCalendarView />
            </div>
        )
    }

    return (
        <div className="space-y-2">
            {viewToggle}
        <ResourcePage<AppointmentsClient>
            pageTitle="Appointments"
            routeKey={APPOINTMENT_ROUTES.INDEX}
            searchable
            searchPlaceholder="Search appointments..."
            statusFilter={{ statuses: AppointmentStatus }}
            getClient={(api) => api.appointments}
            onRowClick={(row) => router.push(`/calendar/appointment/${(row as any).id}`)}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog title="Appointment">
                        {(resourceId) => (
                            <AppointmentForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "title",
                    header: ({ column }) => <ColumnHeader column={column} title="Title" />,
                    cell: ({ row }) => (
                        <div className="flex items-center gap-2">
                            <CalendarCheck2Icon className="size-4 text-muted-foreground" />
                            <span>{(row.original as any).title}</span>
                        </div>
                    ),
                },
                {
                    accessorKey: "date",
                    header: ({ column }) => <ColumnHeader column={column} title="Date" />,
                },
                {
                    accessorKey: "from_time",
                    header: ({ column }) => <ColumnHeader column={column} title="Time" />,
                    cell: ({ row }) => {
                        const r = row.original as any
                        return (
                            <div className="flex items-center gap-1">
                                <ClockIcon className="size-3 text-muted-foreground" />
                                <span>{r.from_time} – {r.to_time}</span>
                            </div>
                        )
                    },
                },
                {
                    accessorKey: "status",
                    header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                    cell: ({ row }) => {
                        const status = (row.original as any).status
                        const colorClass = STATUS_COLORS[status] ?? "bg-gray-100 text-gray-800"
                        return (
                            <Badge className={colorClass}>
                                {formatEnum(status)}
                            </Badge>
                        )
                    },
                },
                {
                    id: "job_card",
                    header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
                    cell: ({ row }) => {
                        const item = row.original as any
                        const jobCardId = item.job_card_id ?? item.job_card?.id
                        return (
                            <RelationLink
                                href={jobCardId ? `/sales/job-cards/${jobCardId}` : null}
                                icon={ClipboardListIcon}
                                label={item.job_card?.title || (jobCardId ? `#${jobCardId}` : null)}
                            />
                        )
                    },
                },
                actionsColumn(),
            ]}
        />
        </div>
    )
}
