"use client"

import { useEffect, useState, useCallback } from "react"
import { useAuth } from "@/contexts/auth-context"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Search, Edit, Save, X, Layers, Plus, Trash2, GripVertical } from "lucide-react"
import { getApiUrl } from "@/lib/api-config"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"

interface SequenceSong {
    position: number
    song_id: number
    song_title: string
}

interface Sequence {
    id: number
    name: string
    slug: string
    description: string | null
    notes: string | null
    songs: SequenceSong[]
}

interface Song {
    id: number
    title: string
    slug: string
}

// Edit Sequence Form Component
function EditSequenceForm({
    sequence,
    allSongs,
    token,
    onSave,
    onCancel
}: {
    sequence: Sequence
    allSongs: Song[]
    token: string
    onSave: () => void
    onCancel: () => void
}) {
    const [name, setName] = useState(sequence.name)
    const [description, setDescription] = useState(sequence.description || "")
    const [notes, setNotes] = useState(sequence.notes || "")
    const [songIds, setSongIds] = useState<number[]>(sequence.songs.map(s => s.song_id))
    const [songSearch, setSongSearch] = useState("")
    const [saving, setSaving] = useState(false)

    const filteredSongs = allSongs.filter(s =>
        s.title.toLowerCase().includes(songSearch.toLowerCase()) &&
        !songIds.includes(s.id)
    ).slice(0, 15)

    const addSong = (id: number) => setSongIds([...songIds, id])
    const removeSong = (id: number) => setSongIds(songIds.filter(sid => sid !== id))
    const moveSong = (index: number, direction: -1 | 1) => {
        const newIds = [...songIds]
        const newIndex = index + direction
        if (newIndex < 0 || newIndex >= newIds.length) return
        [newIds[index], newIds[newIndex]] = [newIds[newIndex], newIds[index]]
        setSongIds(newIds)
    }

    const handleSave = async () => {
        setSaving(true)
        try {
            const res = await fetch(`${getApiUrl()}/sequences/${sequence.id}`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify({ name, description, notes, song_ids: songIds })
            })
            if (res.ok) onSave()
        } catch (e) {
            console.error("Failed to save", e)
        } finally {
            setSaving(false)
        }
    }

    return (
        <div className="space-y-4 py-4">
            <div className="space-y-2">
                <Label>Name *</Label>
                <Input value={name} onChange={e => setName(e.target.value)} />
            </div>
            <div className="space-y-2">
                <Label>Description</Label>
                <Textarea value={description} onChange={e => setDescription(e.target.value)} rows={2} />
            </div>
            <div className="space-y-2">
                <Label>Notes</Label>
                <Textarea value={notes} onChange={e => setNotes(e.target.value)} rows={2} placeholder="Internal notes..." />
            </div>
            <div className="space-y-2">
                <Label>Songs (in order)</Label>
                <div className="border rounded-md p-3 min-h-[60px] bg-muted/20 space-y-1">
                    {songIds.length === 0 ? (
                        <p className="text-sm text-muted-foreground">No songs. Add below.</p>
                    ) : (
                        songIds.map((id, i) => {
                            const song = allSongs.find(s => s.id === id)
                            return (
                                <div key={id} className="flex items-center justify-between bg-background p-2 rounded border">
                                    <span className="text-sm">{i + 1}. {song?.title || `Song ${id}`}</span>
                                    <div className="flex gap-1">
                                        <Button variant="ghost" size="sm" onClick={() => moveSong(i, -1)} disabled={i === 0}>
                                            ↑
                                        </Button>
                                        <Button variant="ghost" size="sm" onClick={() => moveSong(i, 1)} disabled={i === songIds.length - 1}>
                                            ↓
                                        </Button>
                                        <Button variant="ghost" size="sm" onClick={() => removeSong(id)} className="text-red-600">
                                            <X className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            )
                        })
                    )}
                </div>
            </div>
            <div className="space-y-2">
                <Label>Add Songs</Label>
                <Input placeholder="Search songs..." value={songSearch} onChange={e => setSongSearch(e.target.value)} />
                {songSearch && (
                    <div className="border rounded-md max-h-40 overflow-y-auto">
                        {filteredSongs.map(song => (
                            <button key={song.id} className="w-full text-left px-3 py-2 hover:bg-muted/50 border-b last:border-b-0 text-sm" onClick={() => addSong(song.id)}>
                                {song.title}
                            </button>
                        ))}
                    </div>
                )}
            </div>
            <DialogFooter>
                <Button variant="outline" onClick={onCancel}>Cancel</Button>
                <Button onClick={handleSave} disabled={saving || !name}>
                    <Save className="h-4 w-4 mr-2" />
                    {saving ? "Saving..." : "Save Changes"}
                </Button>
            </DialogFooter>
        </div>
    )
}

export default function AdminSequencesPage() {
    const { user, token, loading: authLoading } = useAuth()
    const router = useRouter()
    const [sequences, setSequences] = useState<Sequence[]>([])
    const [allSongs, setAllSongs] = useState<Song[]>([])
    const [loading, setLoading] = useState(true)
    const [search, setSearch] = useState("")
    const [editingSequence, setEditingSequence] = useState<Sequence | null>(null)
    const [isCreating, setIsCreating] = useState(false)
    const [newSequence, setNewSequence] = useState({ name: "", description: "", notes: "", song_ids: [] as number[] })
    const [saving, setSaving] = useState(false)
    const [songSearch, setSongSearch] = useState("")

    const fetchSequences = useCallback(async () => {
        if (!token) return

        try {
            const res = await fetch(`${getApiUrl()}/sequences?limit=1000`, {
                headers: { Authorization: `Bearer ${token}` }
            })
            if (res.ok) setSequences(await res.json())
        } catch (e) {
            console.error("Failed to fetch sequences", e)
        } finally {
            setLoading(false)
        }
    }, [token])

    const fetchSongs = useCallback(async () => {
        if (!token) return

        try {
            const res = await fetch(`${getApiUrl()}/songs?limit=1000`, {
                headers: { Authorization: `Bearer ${token}` }
            })
            if (res.ok) {
                const data = await res.json()
                setAllSongs(data.songs || data)
            }
        } catch (e) {
            console.error("Failed to fetch songs", e)
        }
    }, [token])

    useEffect(() => {
        if (authLoading) return
        if (!user) {
            router.push("/login")
            return
        }
        if (user.role !== "admin") {
            router.push("/")
            return
        }
        fetchSequences()
        fetchSongs()
    }, [user, router, authLoading, fetchSequences, fetchSongs])

    const createSequence = async () => {
        if (!token || !newSequence.name) return
        setSaving(true)

        try {
            const res = await fetch(`${getApiUrl()}/sequences`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify(newSequence)
            })

            if (res.ok) {
                fetchSequences()
                setIsCreating(false)
                setNewSequence({ name: "", description: "", notes: "", song_ids: [] })
            }
        } catch (e) {
            console.error("Failed to create sequence", e)
        } finally {
            setSaving(false)
        }
    }

    const deleteSequence = async (id: number) => {
        if (!token) return
        if (!confirm("Delete this sequence?")) return

        try {
            await fetch(`${getApiUrl()}/sequences/${id}`, {
                method: "DELETE",
                headers: { Authorization: `Bearer ${token}` }
            })
            fetchSequences()
        } catch (e) {
            console.error("Failed to delete sequence", e)
        }
    }

    const addSongToNew = (songId: number) => {
        if (!newSequence.song_ids.includes(songId)) {
            setNewSequence({ ...newSequence, song_ids: [...newSequence.song_ids, songId] })
        }
    }

    const removeSongFromNew = (songId: number) => {
        setNewSequence({ ...newSequence, song_ids: newSequence.song_ids.filter(id => id !== songId) })
    }

    const filteredSequences = sequences.filter(s =>
        s.name.toLowerCase().includes(search.toLowerCase())
    )

    const filteredSongs = allSongs.filter(s =>
        s.title.toLowerCase().includes(songSearch.toLowerCase())
    ).slice(0, 20)

    if (loading) {
        return (
            <div className="space-y-4">
                <div className="h-8 bg-muted rounded w-48 animate-pulse" />
                <div className="grid gap-4">
                    {[1, 2, 3].map(i => <div key={i} className="h-20 bg-muted rounded animate-pulse" />)}
                </div>
            </div>
        )
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold flex items-center gap-2">
                    <Layers className="h-6 w-6" />
                    Sequence Management
                </h2>
                <Button onClick={() => setIsCreating(true)}>
                    <Plus className="h-4 w-4 mr-2" />
                    Add Sequence
                </Button>
            </div>

            <p className="text-muted-foreground text-sm">
                Sequences are named groupings of consecutive songs, like &quot;Autumn Crossing&quot; (Travelers &gt; Elmeg the Wise).
            </p>

            <div className="relative max-w-sm">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                    placeholder="Search sequences..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="pl-9"
                />
            </div>

            <Card>
                <CardContent className="p-0">
                    <table className="w-full">
                        <thead className="bg-muted/50">
                            <tr>
                                <th className="text-left p-3 font-medium">Sequence Name</th>
                                <th className="text-left p-3 font-medium">Songs</th>
                                <th className="text-right p-3 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredSequences.map(seq => (
                                <tr key={seq.id} className="border-t">
                                    <td className="p-3">
                                        <p className="font-medium">{seq.name}</p>
                                        {seq.description && (
                                            <p className="text-sm text-muted-foreground">{seq.description}</p>
                                        )}
                                    </td>
                                    <td className="p-3">
                                        <div className="flex flex-wrap gap-1">
                                            {seq.songs.map((s, i) => (
                                                <span key={s.song_id} className="text-sm">
                                                    {s.song_title}
                                                    {i < seq.songs.length - 1 && <span className="text-muted-foreground mx-1">&gt;</span>}
                                                </span>
                                            ))}
                                            {seq.songs.length === 0 && (
                                                <Badge variant="outline" className="text-yellow-600 border-yellow-600">No songs</Badge>
                                            )}
                                        </div>
                                    </td>
                                    <td className="p-3 text-right space-x-1">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setEditingSequence(seq)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="text-red-600 hover:text-red-700"
                                            onClick={() => deleteSequence(seq.id)}
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    {filteredSequences.length === 0 && (
                        <div className="p-8 text-center text-muted-foreground">
                            No sequences found. Create one to get started!
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Create Dialog */}
            <Dialog open={isCreating} onOpenChange={setIsCreating}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Create New Sequence</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label>Sequence Name *</Label>
                            <Input
                                placeholder="e.g., Autumn Crossing"
                                value={newSequence.name}
                                onChange={(e) => setNewSequence({ ...newSequence, name: e.target.value })}
                            />
                        </div>

                        <div className="space-y-2">
                            <Label>Description</Label>
                            <Textarea
                                placeholder="Brief description of this sequence..."
                                value={newSequence.description}
                                onChange={(e) => setNewSequence({ ...newSequence, description: e.target.value })}
                                rows={2}
                            />
                        </div>

                        <div className="space-y-2">
                            <Label>Songs in Sequence (in order)</Label>
                            <div className="border rounded-md p-3 min-h-[60px] bg-muted/20">
                                {newSequence.song_ids.length === 0 ? (
                                    <p className="text-sm text-muted-foreground">No songs added yet. Search and add songs below.</p>
                                ) : (
                                    <div className="flex flex-wrap gap-2">
                                        {newSequence.song_ids.map((id, i) => {
                                            const song = allSongs.find(s => s.id === id)
                                            return (
                                                <Badge key={id} variant="secondary" className="flex items-center gap-1">
                                                    <GripVertical className="h-3 w-3 text-muted-foreground" />
                                                    {i + 1}. {song?.title || `Song ${id}`}
                                                    <button onClick={() => removeSongFromNew(id)} className="ml-1 hover:text-red-600">
                                                        <X className="h-3 w-3" />
                                                    </button>
                                                </Badge>
                                            )
                                        })}
                                    </div>
                                )}
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label>Search Songs to Add</Label>
                            <Input
                                placeholder="Type to search songs..."
                                value={songSearch}
                                onChange={(e) => setSongSearch(e.target.value)}
                            />
                            {songSearch && (
                                <div className="border rounded-md max-h-48 overflow-y-auto">
                                    {filteredSongs.map(song => (
                                        <button
                                            key={song.id}
                                            className="w-full text-left px-3 py-2 hover:bg-muted/50 border-b last:border-b-0"
                                            onClick={() => addSongToNew(song.id)}
                                        >
                                            {song.title}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setIsCreating(false)}>
                            Cancel
                        </Button>
                        <Button onClick={createSequence} disabled={saving || !newSequence.name}>
                            <Save className="h-4 w-4 mr-2" />
                            {saving ? "Creating..." : "Create Sequence"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Edit Dialog */}
            <Dialog open={!!editingSequence} onOpenChange={() => setEditingSequence(null)}>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>Edit Sequence</DialogTitle>
                    </DialogHeader>
                    {editingSequence && (
                        <EditSequenceForm
                            sequence={editingSequence}
                            allSongs={allSongs}
                            token={token!}
                            onSave={() => {
                                fetchSequences()
                                setEditingSequence(null)
                            }}
                            onCancel={() => setEditingSequence(null)}
                        />
                    )}
                </DialogContent>
            </Dialog>
        </div>
    )
}
