'use client'

import { useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  LayoutTemplate,
  Plus,
  Calendar,
  Settings2,
  Trash2,
  Loader2,
} from 'lucide-react'
import { toast } from 'sonner'

const ROUND_TYPE_LABELS: Record<string, string> = {
  FILTERING: 'Filtering',
  EVALUATION: 'Evaluation',
  LIVE_EVENT: 'Live Event',
}

const ROUND_TYPE_COLORS: Record<string, 'default' | 'secondary' | 'outline'> = {
  FILTERING: 'secondary',
  EVALUATION: 'default',
  LIVE_EVENT: 'outline',
}

export default function RoundTemplatesPage() {
  const utils = trpc.useUtils()
  const { data: templates, isLoading } = trpc.roundTemplate.list.useQuery()
  const [createOpen, setCreateOpen] = useState(false)
  const [newName, setNewName] = useState('')
  const [newDescription, setNewDescription] = useState('')
  const [newRoundType, setNewRoundType] = useState('EVALUATION')
  const [deleteId, setDeleteId] = useState<string | null>(null)

  const createTemplate = trpc.roundTemplate.create.useMutation({
    onSuccess: () => {
      utils.roundTemplate.list.invalidate()
      setCreateOpen(false)
      setNewName('')
      setNewDescription('')
      setNewRoundType('EVALUATION')
      toast.success('Template created')
    },
    onError: (err) => {
      toast.error(err.message)
    },
  })

  const deleteTemplate = trpc.roundTemplate.delete.useMutation({
    onSuccess: () => {
      utils.roundTemplate.list.invalidate()
      setDeleteId(null)
      toast.success('Template deleted')
    },
    onError: (err) => {
      toast.error(err.message)
    },
  })

  const handleCreate = () => {
    if (!newName.trim()) return
    createTemplate.mutate({
      name: newName.trim(),
      description: newDescription.trim() || undefined,
      roundType: newRoundType as 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT',
      criteriaJson: [],
    })
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <Skeleton className="h-9 w-48" />
          <Skeleton className="h-9 w-40" />
        </div>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {[...Array(3)].map((_, i) => (
            <Skeleton key={i} className="h-40" />
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            Round Templates
          </h1>
          <p className="text-muted-foreground">
            Save and reuse round configurations across editions
          </p>
        </div>
        <Dialog open={createOpen} onOpenChange={setCreateOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              New Template
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create Template</DialogTitle>
              <DialogDescription>
                Create a blank template. You can also save an existing round as a template from the round detail page.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-2">
              <div className="space-y-2">
                <Label htmlFor="template-name">Name</Label>
                <Input
                  id="template-name"
                  placeholder="e.g., Standard Evaluation Round"
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="template-description">Description</Label>
                <Textarea
                  id="template-description"
                  placeholder="Describe what this template is for..."
                  value={newDescription}
                  onChange={(e) => setNewDescription(e.target.value)}
                  rows={3}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="template-type">Round Type</Label>
                <Select value={newRoundType} onValueChange={setNewRoundType}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(ROUND_TYPE_LABELS).map(([value, label]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setCreateOpen(false)}>
                Cancel
              </Button>
              <Button
                onClick={handleCreate}
                disabled={!newName.trim() || createTemplate.isPending}
              >
                {createTemplate.isPending && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                Create
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Templates Grid */}
      {templates && templates.length > 0 ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {templates.map((template) => {
            const criteria = (template.criteriaJson as Array<unknown>) || []
            const hasSettings = template.settingsJson && Object.keys(template.settingsJson as object).length > 0

            return (
              <Card key={template.id} className="group relative transition-colors hover:bg-muted/50">
                <Link href={`/admin/round-templates/${template.id}`}>
                  <CardHeader className="pb-3">
                    <div className="flex items-start justify-between">
                      <CardTitle className="text-lg flex items-center gap-2">
                        <LayoutTemplate className="h-5 w-5 text-primary" />
                        {template.name}
                      </CardTitle>
                      <Badge variant={ROUND_TYPE_COLORS[template.roundType] || 'secondary'}>
                        {ROUND_TYPE_LABELS[template.roundType] || template.roundType}
                      </Badge>
                    </div>
                    {template.description && (
                      <CardDescription className="line-clamp-2">
                        {template.description}
                      </CardDescription>
                    )}
                  </CardHeader>
                  <CardContent>
                    <div className="flex items-center gap-4 text-sm text-muted-foreground">
                      <div className="flex items-center gap-1">
                        <Settings2 className="h-4 w-4" />
                        {criteria.length} criteria
                      </div>
                      {hasSettings && (
                        <Badge variant="outline" className="text-xs">
                          Custom settings
                        </Badge>
                      )}
                      <div className="flex items-center gap-1 ml-auto">
                        <Calendar className="h-3.5 w-3.5" />
                        {new Date(template.createdAt).toLocaleDateString()}
                      </div>
                    </div>
                  </CardContent>
                </Link>
                {/* Delete button */}
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity h-8 w-8"
                  onClick={(e) => {
                    e.preventDefault()
                    e.stopPropagation()
                    setDeleteId(template.id)
                  }}
                >
                  <Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
                </Button>
              </Card>
            )
          })}
        </div>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <LayoutTemplate className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No templates yet</p>
            <p className="text-sm text-muted-foreground">
              Create a template or save an existing round configuration as a template
            </p>
            <Button className="mt-4" onClick={() => setCreateOpen(true)}>
              <Plus className="mr-2 h-4 w-4" />
              Create Template
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Template</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this template? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={() => deleteId && deleteTemplate.mutate({ id: deleteId })}
              disabled={deleteTemplate.isPending}
            >
              {deleteTemplate.isPending && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              Delete
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
