'use client'

import { useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
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 { Checkbox } from '@/components/ui/checkbox'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  ArrowLeft,
  Plus,
  Pencil,
  Trash2,
  Loader2,
  ChevronUp,
  ChevronDown,
  Target,
  Calendar,
} from 'lucide-react'
import { toast } from 'sonner'

interface MilestoneFormData {
  name: string
  description: string
  isRequired: boolean
  deadlineOffsetDays: number
  sortOrder: number
}

const defaultMilestoneForm: MilestoneFormData = {
  name: '',
  description: '',
  isRequired: false,
  deadlineOffsetDays: 30,
  sortOrder: 0,
}

export default function MentorshipMilestonesPage() {
  const params = useParams()
  const router = useRouter()
  const programId = params.id as string

  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [formData, setFormData] = useState<MilestoneFormData>(defaultMilestoneForm)

  const utils = trpc.useUtils()

  const { data: milestones, isLoading } = trpc.mentor.getMilestones.useQuery({ programId })

  const createMutation = trpc.mentor.createMilestone.useMutation({
    onSuccess: () => {
      utils.mentor.getMilestones.invalidate({ programId })
      toast.success('Milestone created')
      closeDialog()
    },
    onError: (e) => toast.error(e.message),
  })

  const updateMutation = trpc.mentor.updateMilestone.useMutation({
    onSuccess: () => {
      utils.mentor.getMilestones.invalidate({ programId })
      toast.success('Milestone updated')
      closeDialog()
    },
    onError: (e) => toast.error(e.message),
  })

  const deleteMutation = trpc.mentor.deleteMilestone.useMutation({
    onSuccess: () => {
      utils.mentor.getMilestones.invalidate({ programId })
      toast.success('Milestone deleted')
      setDeleteId(null)
    },
    onError: (e) => toast.error(e.message),
  })

  const reorderMutation = trpc.mentor.reorderMilestones.useMutation({
    onSuccess: () => utils.mentor.getMilestones.invalidate({ programId }),
    onError: (e) => toast.error(e.message),
  })

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

  const openEdit = (milestone: Record<string, unknown>) => {
    setEditingId(String(milestone.id))
    setFormData({
      name: String(milestone.name || ''),
      description: String(milestone.description || ''),
      isRequired: Boolean(milestone.isRequired),
      deadlineOffsetDays: Number(milestone.deadlineOffsetDays || 30),
      sortOrder: Number(milestone.sortOrder || 0),
    })
    setDialogOpen(true)
  }

  const openCreate = () => {
    const nextOrder = milestones ? (milestones as unknown[]).length : 0
    setFormData({ ...defaultMilestoneForm, sortOrder: nextOrder })
    setEditingId(null)
    setDialogOpen(true)
  }

  const handleSubmit = () => {
    if (!formData.name.trim()) {
      toast.error('Milestone name is required')
      return
    }

    if (editingId) {
      updateMutation.mutate({
        milestoneId: editingId,
        name: formData.name.trim(),
        description: formData.description.trim() || undefined,
        isRequired: formData.isRequired,
        deadlineOffsetDays: formData.deadlineOffsetDays,
        sortOrder: formData.sortOrder,
      })
    } else {
      createMutation.mutate({
        programId,
        name: formData.name.trim(),
        description: formData.description.trim() || undefined,
        isRequired: formData.isRequired,
        deadlineOffsetDays: formData.deadlineOffsetDays,
        sortOrder: formData.sortOrder,
      })
    }
  }

  const moveMilestone = (id: string, direction: 'up' | 'down') => {
    if (!milestones) return
    const list = milestones as Array<Record<string, unknown>>
    const index = list.findIndex((m) => String(m.id) === id)
    if (index === -1) return
    if (direction === 'up' && index === 0) return
    if (direction === 'down' && index === list.length - 1) return

    const ids = list.map((m) => String(m.id))
    const [moved] = ids.splice(index, 1)
    ids.splice(direction === 'up' ? index - 1 : index + 1, 0, moved)

    reorderMutation.mutate({ milestoneIds: ids })
  }

  const isPending = createMutation.isPending || updateMutation.isPending

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" className="-ml-4" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
      </div>

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            Mentorship Milestones
          </h1>
          <p className="text-muted-foreground">
            Configure milestones for the mentorship program
          </p>
        </div>
        <Dialog open={dialogOpen} onOpenChange={(open) => !open && closeDialog()}>
          <DialogTrigger asChild>
            <Button onClick={openCreate}>
              <Plus className="mr-2 h-4 w-4" />
              Add Milestone
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editingId ? 'Edit Milestone' : 'Add Milestone'}</DialogTitle>
              <DialogDescription>
                Configure a milestone for the mentorship program.
              </DialogDescription>
            </DialogHeader>

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

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

              <div className="flex items-center gap-2">
                <Checkbox
                  id="milestone-required"
                  checked={formData.isRequired}
                  onCheckedChange={(checked) =>
                    setFormData({ ...formData, isRequired: !!checked })
                  }
                />
                <label htmlFor="milestone-required" className="text-sm cursor-pointer">
                  Required milestone
                </label>
              </div>

              <div className="space-y-2">
                <Label>Deadline Offset (days from program start)</Label>
                <Input
                  type="number"
                  min={1}
                  max={365}
                  value={formData.deadlineOffsetDays}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      deadlineOffsetDays: parseInt(e.target.value) || 30,
                    })
                  }
                />
              </div>
            </div>

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

      {/* Milestones list */}
      {isLoading ? (
        <MilestonesSkeleton />
      ) : milestones && (milestones as unknown[]).length > 0 ? (
        <div className="space-y-2">
          {(milestones as Array<Record<string, unknown>>).map((milestone, index) => {
            const completions = milestone.completions as Array<unknown> | undefined
            const completionCount = completions ? completions.length : 0

            return (
              <Card key={String(milestone.id)}>
                <CardContent className="p-4">
                  <div className="flex items-center gap-3">
                    {/* Order number and reorder buttons */}
                    <div className="flex flex-col items-center gap-0.5">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-5 w-5"
                        disabled={index === 0 || reorderMutation.isPending}
                        onClick={() => moveMilestone(String(milestone.id), 'up')}
                      >
                        <ChevronUp className="h-3 w-3" />
                      </Button>
                      <span className="text-xs font-medium text-muted-foreground w-5 text-center">
                        {index + 1}
                      </span>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-5 w-5"
                        disabled={
                          index === (milestones as unknown[]).length - 1 ||
                          reorderMutation.isPending
                        }
                        onClick={() => moveMilestone(String(milestone.id), 'down')}
                      >
                        <ChevronDown className="h-3 w-3" />
                      </Button>
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="font-medium">{String(milestone.name)}</span>
                        {!!milestone.isRequired && (
                          <Badge variant="default" className="text-xs">Required</Badge>
                        )}
                        <Badge variant="outline" className="text-xs">
                          <Calendar className="mr-1 h-3 w-3" />
                          Day {String(milestone.deadlineOffsetDays || 30)}
                        </Badge>
                        {completionCount > 0 && (
                          <Badge variant="secondary" className="text-xs">
                            {completionCount} completions
                          </Badge>
                        )}
                      </div>
                      {!!milestone.description && (
                        <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                          {String(milestone.description)}
                        </p>
                      )}
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => openEdit(milestone)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setDeleteId(String(milestone.id))}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      ) : (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12 text-center">
            <Target className="h-12 w-12 text-muted-foreground/50" />
            <p className="mt-2 font-medium">No milestones defined</p>
            <p className="text-sm text-muted-foreground">
              Add milestones to track mentor-mentee progress.
            </p>
          </CardContent>
        </Card>
      )}

      {/* Delete confirmation */}
      <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Milestone</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete this milestone? Progress data associated
              with it may be lost.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() =>
                deleteId && deleteMutation.mutate({ milestoneId: 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 MilestonesSkeleton() {
  return (
    <div className="space-y-2">
      {[1, 2, 3].map((i) => (
        <Card key={i}>
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <Skeleton className="h-16 w-6" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-5 w-48" />
                <Skeleton className="h-4 w-full" />
              </div>
              <Skeleton className="h-8 w-16" />
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
