'use client'

import { useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  ArrowLeft,
  Plus,
  Pencil,
  Trash2,
  Copy,
  Loader2,
  LayoutTemplate,
} from 'lucide-react'
import { toast } from 'sonner'
import { formatDate } from '@/lib/utils'

const ROUND_TYPES = [
  { value: 'EVALUATION', label: 'Evaluation' },
  { value: 'FILTERING', label: 'Filtering' },
  { value: 'LIVE_EVENT', label: 'Live Event' },
]

interface TemplateFormData {
  name: string
  description: string
  roundType: string
  programId: string
  criteriaJson: string
  settingsJson: string
}

const defaultForm: TemplateFormData = {
  name: '',
  description: '',
  roundType: 'EVALUATION',
  programId: '',
  criteriaJson: '[]',
  settingsJson: '{}',
}

export default function RoundTemplatesPage() {
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [formData, setFormData] = useState<TemplateFormData>(defaultForm)

  const utils = trpc.useUtils()

  const { data: templates, isLoading } = trpc.roundTemplate.list.useQuery()
  const { data: programs } = trpc.program.list.useQuery()

  const createMutation = trpc.roundTemplate.create.useMutation({
    onSuccess: () => {
      utils.roundTemplate.list.invalidate()
      toast.success('Template created')
      closeDialog()
    },
    onError: (e) => toast.error(e.message),
  })

  const updateMutation = trpc.roundTemplate.update.useMutation({
    onSuccess: () => {
      utils.roundTemplate.list.invalidate()
      toast.success('Template updated')
      closeDialog()
    },
    onError: (e) => toast.error(e.message),
  })

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

  const closeDialog = () => {
    setDialogOpen(false)
    setEditingId(null)
    setFormData(defaultForm)
  }

  const openEdit = (template: Record<string, unknown>) => {
    setEditingId(String(template.id))
    setFormData({
      name: String(template.name || ''),
      description: String(template.description || ''),
      roundType: String(template.roundType || 'EVALUATION'),
      programId: String(template.programId || ''),
      criteriaJson: JSON.stringify(template.criteriaJson || [], null, 2),
      settingsJson: JSON.stringify(template.settingsJson || {}, null, 2),
    })
    setDialogOpen(true)
  }

  const handleSubmit = () => {
    let criteriaJson: unknown
    let settingsJson: unknown

    try {
      criteriaJson = JSON.parse(formData.criteriaJson)
    } catch {
      toast.error('Invalid criteria JSON')
      return
    }

    try {
      settingsJson = JSON.parse(formData.settingsJson)
    } catch {
      toast.error('Invalid settings JSON')
      return
    }

    const payload = {
      name: formData.name,
      description: formData.description || undefined,
      roundType: formData.roundType as 'FILTERING' | 'EVALUATION' | 'LIVE_EVENT',
      programId: formData.programId || undefined,
      criteriaJson,
      settingsJson,
    }

    if (editingId) {
      updateMutation.mutate({ id: editingId, ...payload })
    } else {
      createMutation.mutate(payload)
    }
  }

  const isPending = createMutation.isPending || updateMutation.isPending

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" asChild className="-ml-4">
          <Link href="/admin/settings">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Settings
          </Link>
        </Button>
      </div>

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Round Templates</h1>
          <p className="text-muted-foreground">
            Create reusable templates for round configuration
          </p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
          <DialogTrigger asChild>
            <Button onClick={() => { setFormData(defaultForm); setEditingId(null); setDialogOpen(true) }}>
              <Plus className="mr-2 h-4 w-4" />
              Create Template
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editingId ? 'Edit Template' : 'Create Template'}</DialogTitle>
              <DialogDescription>
                {editingId
                  ? 'Update the template configuration.'
                  : 'Define a reusable round template.'}
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Template Name</Label>
                <Input
                  placeholder="e.g., Standard Evaluation Round"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea
                  placeholder="Template description..."
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  rows={2}
                />
              </div>

              <div className="space-y-2">
                <Label>Round Type</Label>
                <Select
                  value={formData.roundType}
                  onValueChange={(v) => setFormData({ ...formData, roundType: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {ROUND_TYPES.map((rt) => (
                      <SelectItem key={rt.value} value={rt.value}>
                        {rt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>Program (optional)</Label>
                <Select
                  value={formData.programId}
                  onValueChange={(v) => setFormData({ ...formData, programId: v === '__none__' ? '' : v })}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Global (all programs)" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">Global (all programs)</SelectItem>
                    {(programs as Array<{ id: string; name: string }> | undefined)?.map((p) => (
                      <SelectItem key={p.id} value={p.id}>
                        {p.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>Criteria (JSON)</Label>
                <Textarea
                  value={formData.criteriaJson}
                  onChange={(e) => setFormData({ ...formData, criteriaJson: e.target.value })}
                  rows={5}
                  className="font-mono text-sm"
                  placeholder='[{"name":"Innovation","maxScore":10,"weight":1}]'
                />
              </div>

              <div className="space-y-2">
                <Label>Settings (JSON)</Label>
                <Textarea
                  value={formData.settingsJson}
                  onChange={(e) => setFormData({ ...formData, settingsJson: e.target.value })}
                  rows={3}
                  className="font-mono text-sm"
                  placeholder='{"requiredReviews":3}'
                />
              </div>
            </div>

            <DialogFooter>
              <Button variant="outline" onClick={closeDialog}>
                Cancel
              </Button>
              <Button onClick={handleSubmit} disabled={!formData.name || isPending}>
                {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {editingId ? 'Update' : 'Create'}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* Templates list */}
      {isLoading ? (
        <TemplatesSkeleton />
      ) : templates && (templates as unknown[]).length > 0 ? (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead className="hidden md:table-cell">Round Type</TableHead>
                <TableHead className="hidden md:table-cell">Program</TableHead>
                <TableHead className="hidden lg:table-cell">Created</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {(templates as Array<Record<string, unknown>>).map((template) => (
                <TableRow key={String(template.id)}>
                  <TableCell>
                    <div>
                      <p className="font-medium">{String(template.name)}</p>
                      {!!template.description && (
                        <p className="text-sm text-muted-foreground line-clamp-1">
                          {String(template.description)}
                        </p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="hidden md:table-cell">
                    <Badge variant="secondary">
                      {String(template.roundType || 'EVALUATION')}
                    </Badge>
                  </TableCell>
                  <TableCell className="hidden md:table-cell">
                    {template.program
                      ? String((template.program as Record<string, unknown>).name)
                      : 'Global'}
                  </TableCell>
                  <TableCell className="hidden lg:table-cell text-sm text-muted-foreground">
                    {template.createdAt ? formatDate(template.createdAt as string | Date) : ''}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => openEdit(template)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setDeleteId(String(template.id))}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      ) : (
        <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 to reuse round configurations across programs.
            </p>
          </CardContent>
        </Card>
      )}

      {/* Delete confirmation */}
      <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Template</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this template? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteId && deleteMutation.mutate({ id: deleteId })}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}

function TemplatesSkeleton() {
  return (
    <Card>
      <CardContent className="p-6">
        <div className="space-y-4">
          {[1, 2, 3].map((i) => (
            <div key={i} className="flex items-center gap-4">
              <Skeleton className="h-4 w-40" />
              <Skeleton className="h-6 w-24" />
              <Skeleton className="h-4 w-20" />
              <Skeleton className="h-8 w-16 ml-auto" />
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}
