import { Box, Card, CardContent, Typography } from '@mui/material'
import Grid from '@mui/material/Grid'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../lib/api'

import {
    DndContext,
    closestCenter,
    DragEndEvent,
    PointerSensor,
    useSensor,
    useSensors,
} from '@dnd-kit/core'
import {
    arrayMove,
    SortableContext,
    useSortable,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import DragIndicatorIcon from '@mui/icons-material/DragIndicator'

interface HomeworkType {
    id: number
    title: string
    description: string
    reset_type: string
    clear_count: number
}

function SortableHomeworkCard({ homework }: { homework: HomeworkType }) {
    const navigate = useNavigate()
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
        id: homework.id,
    })

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        zIndex: isDragging ? 1000 : 'auto',
        position: 'relative' as const,
    }

    return (
        <Grid item xs={12} sm={6} md={4} ref={setNodeRef} style={style} {...({} as any)}>
            <Card
                sx={{
                    cursor: 'pointer',
                    textDecoration: 'none',
                    position: 'relative',
                }}
                onClick={() => navigate(`/homeworks/${homework.id}/edit`)}
            >
                <Box
                    {...attributes}
                    {...listeners}
                    sx={{
                        position: 'absolute',
                        top: 8,
                        right: 8,
                        width: 24,
                        height: 24,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        backgroundColor: 'rgba(0,0,0,0.1)',
                        borderRadius: '50%',
                        cursor: 'grab',
                        zIndex: 10,
                    }}
                    onClick={(e) => e.stopPropagation()}
                >
                    <DragIndicatorIcon fontSize="small" />
                </Box>

                <CardContent>
                    <Typography variant="h6">{homework.title}</Typography>
                    <Typography>주기: {homework.reset_type}</Typography>
                    <Typography>횟수: {homework.clear_count}</Typography>
                </CardContent>
            </Card>
        </Grid>
    )
}

export default function HomeworkList() {
    const [homeworks, setHomeworks] = useState<HomeworkType[]>([])

    useEffect(() => {
        api.get('/homeworks').then((res) => setHomeworks(res.data))
    }, [])

    const sensors = useSensors(useSensor(PointerSensor))

    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event
        if (!over || active.id === over.id) return

        const oldIndex = homeworks.findIndex((h) => h.id === active.id)
        const newIndex = homeworks.findIndex((h) => h.id === over.id)
        const newOrder = arrayMove(homeworks, oldIndex, newIndex)
        setHomeworks(newOrder)

        const payload = newOrder.map((hw, idx) => ({
            id: hw.id,
            order: idx + 1,
        }))
        api.patch('/homeworks/order', payload)
    }

    return (
        <Box sx={{ p: 4 }}>
            <Typography variant="h5" gutterBottom>
                숙제 목록
            </Typography>
            <DndContext collisionDetection={closestCenter} sensors={sensors} onDragEnd={handleDragEnd}>
                <SortableContext items={homeworks.map((h) => h.id)} strategy={verticalListSortingStrategy}>
                    <Grid container spacing={2}>
                        {homeworks.map((hw) => (
                            <SortableHomeworkCard key={hw.id} homework={hw} />
                        ))}
                        <Grid item xs={12} sm={6} md={4} {...({} as any)}>
                            <Card
                                onClick={() => (window.location.href = '/homeworks/register')}
                                sx={{
                                    height: '100%',
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'center',
                                    textDecoration: 'none',
                                    cursor: 'pointer',
                                }}
                            >
                                <CardContent>
                                    <Typography variant="h6" align="center">
                                        + 숙제 추가
                                    </Typography>
                                </CardContent>
                            </Card>
                        </Grid>
                    </Grid>
                </SortableContext>
            </DndContext>
        </Box>
    )
}
