import { Box, Card, CardContent, Typography, Container } from '@mui/material'
import { Grid } from '@mui/material'
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 Character {
    id: number
    name: string
    server?: string
    job?: string
    combat_power?: number
}

function SortableCharacterCard({ character }: { character: Character }) {
    const navigate = useNavigate()
    const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: character.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} {...({} as any)}>
            <Box ref={setNodeRef} style={style}>
                <Card
                    sx={{
                        cursor: 'pointer',
                        textDecoration: 'none',
                        position: 'relative',
                    }}
                    onClick={() => navigate(`/characters/${character.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">{character.name}</Typography>
                        <Typography color="text.secondary">서버: {character.server || '-'}</Typography>
                        <Typography color="text.secondary">직업: {character.job || '-'}</Typography>
                        <Typography color="text.secondary">
                            전투력: {character.combat_power?.toLocaleString() || '-'}
                        </Typography>
                    </CardContent>
                </Card>
            </Box>
        </Grid>
    )
}

export default function CharacterList() {
    const [characters, setCharacters] = useState<Character[]>([])

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

    const sensors = useSensors(useSensor(PointerSensor))

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

        const oldIndex = characters.findIndex((c) => c.id === active.id)
        const newIndex = characters.findIndex((c) => c.id === over.id)

        const newCharacters = arrayMove(characters, oldIndex, newIndex)
        setCharacters(newCharacters)

        const payload = newCharacters.map((c, index) => ({
            id: c.id,
            order: index + 1,
        }))
        api.patch('/characters/order', payload)
    }

    return (
        <Container sx={{ mt: 4 }}>
            <Typography variant="h5" gutterBottom>
                캐릭터 목록
            </Typography>
            <DndContext collisionDetection={closestCenter} sensors={sensors} onDragEnd={handleDragEnd}>
                <SortableContext items={characters.map((c) => c.id)} strategy={verticalListSortingStrategy}>
                    <Grid container spacing={2}>
                        {characters.map((char) => (
                            <SortableCharacterCard key={char.id} character={char} />
                        ))}
                        <Grid item xs={12} sm={6} md={4} {...({} as any)}>
                            <Card
                                onClick={() => (window.location.href = '/characters/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>
        </Container>
    )
}
