"use client"

import { useParams } from "next/navigation"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { type ColumnDef } from "@tanstack/react-table"
import { useState } from "react"
import { Plus, Trash2, StickyNote } from "lucide-react"
import { toast } from "sonner"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"

import { useAuthApi } from "@/shared/useApi"
import { DataTable, ColumnHeader } from "@/shared/data-view/table-view"
import { confirm } from "@/shared/components/confirm-dialog"
import { Button } from "@/shared/components/ui/button"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/shared/components/ui/dialog"
import {
    Field,
    FieldLabel,
    FieldError,
} from "@/shared/components/ui/field"
import { Textarea } from "@/shared/components/ui/textarea"
import DashboardPage from "@/base/components/layout/dashboard/dashboard-page"

type CustomerNote = {
    id: number
    note: string
    created_at: string
    updated_at: string
}

const addNoteSchema = z.object({
    note: z.string().min(1, "Note content is required"),
})
type AddNoteValues = z.infer<typeof addNoteSchema>

export default function CustomerNotesPage() {
    const { id: customerId } = useParams<{ id: string }>()
    const api = useAuthApi()
    const queryClient = useQueryClient()
    const [dialogOpen, setDialogOpen] = useState(false)

    const queryKey = ["customer-notes", customerId]

    const { data: customerData, isLoading } = useQuery({
        queryKey,
        queryFn: () => api.customers.getById(customerId),
    })

    const notes: CustomerNote[] = (customerData?.data as any)?.notes ?? []

    const meta = (customerData as any)?.meta
    const pagination = {
        page: meta?.current_page ?? 1,
        pageSize: meta?.per_page ?? 15,
        pageCount: meta?.last_page ?? 1,
        total: meta?.total ?? notes.length,
    }

    const addNoteMutation = useMutation({
        mutationFn: (values: AddNoteValues) =>
            api.customers.addNote(customerId, { note: values.note }),
        onSuccess: () => {
            toast.success("Note added successfully.")
            queryClient.invalidateQueries({ queryKey })
            setDialogOpen(false)
            reset()
        },
        onError: () => {
            toast.error("Failed to add note.")
        },
    })

    const deleteNoteMutation = useMutation({
        mutationFn: (noteId: number) => api.customers.deleteNote(customerId, noteId),
        onSuccess: () => {
            toast.success("Note deleted successfully.")
            queryClient.invalidateQueries({ queryKey })
        },
        onError: () => {
            toast.error("Failed to delete note.")
        },
    })

    const {
        handleSubmit,
        register,
        reset,
        formState: { errors },
    } = useForm<AddNoteValues>({
        resolver: zodResolver(addNoteSchema),
        defaultValues: { note: "" },
    })

    const handleDelete = async (note: CustomerNote) => {
        const confirmed = await confirm({
            title: "Delete Note",
            description: "Are you sure you want to delete this note?",
            confirmLabel: "Delete",
            variant: "destructive",
        })
        if (confirmed) {
            deleteNoteMutation.mutate(note.id)
        }
    }

    const columns: ColumnDef<CustomerNote>[] = [
        {
            accessorKey: "note",
            header: ({ column }) => <ColumnHeader column={column} title="Note" />,
            cell: ({ getValue }) => (
                <span className="whitespace-pre-wrap text-sm">{getValue<string>()}</span>
            ),
        },
        {
            accessorKey: "created_at",
            header: ({ column }) => <ColumnHeader column={column} title="Created At" />,
            cell: ({ getValue }) => {
                const val = getValue<string>()
                return val ? new Date(val).toLocaleDateString() : "—"
            },
        },
        {
            id: "actions",
            header: () => <span className="sr-only">Actions</span>,
            cell: ({ row }) => (
                <div className="flex justify-end">
                    <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDelete(row.original)}
                        disabled={deleteNoteMutation.isPending}
                    >
                        <Trash2 className="size-4 text-destructive" />
                    </Button>
                </div>
            ),
        },
    ]

    return (
        <DashboardPage
            headerProps={{
                title: "Notes",
                actions: (
                    <Button size="sm" onClick={() => setDialogOpen(true)}>
                        <Plus className="size-4" />
                        Add Note
                    </Button>
                ),
            }}
        >
            <DataTable
                columns={columns}
                data={notes}
                pagination={pagination}
                sorting={[]}
                onChange={() => {}}
                isLoading={isLoading}
            />

            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Add Note</DialogTitle>
                    </DialogHeader>
                    <form
                        onSubmit={handleSubmit((values) => addNoteMutation.mutate(values))}
                        className="grid gap-4"
                    >
                        <Field>
                            <FieldLabel>Note</FieldLabel>
                            <Textarea
                                {...register("note")}
                                placeholder="Enter note..."
                                rows={4}
                            />
                            {errors.note && <FieldError>{errors.note.message}</FieldError>}
                        </Field>
                        <div className="flex justify-end gap-2">
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setDialogOpen(false)
                                    reset()
                                }}
                            >
                                Cancel
                            </Button>
                            <Button type="submit" disabled={addNoteMutation.isPending}>
                                {addNoteMutation.isPending ? "Saving..." : "Save Note"}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </DashboardPage>
    )
}

