'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { toast } from 'sonner'
import { TagInput } from '@/components/shared/tag-input'
import {
  ArrowLeft,
  Save,
  Mail,
  GraduationCap,
  Loader2,
  AlertCircle,
  ClipboardList,
  User,
} from 'lucide-react'

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

  const { data: mentor, isLoading, refetch } = trpc.user.get.useQuery({ id: mentorId })
  const updateUser = trpc.user.update.useMutation()
  const sendInvitation = trpc.user.sendInvitation.useMutation()
  const { data: assignmentsData } = trpc.mentor.listAssignments.useQuery({
    mentorId,
    perPage: 50,
  })

  const [name, setName] = useState('')
  const [status, setStatus] = useState<'INVITED' | 'ACTIVE' | 'SUSPENDED'>('INVITED')
  const [expertiseTags, setExpertiseTags] = useState<string[]>([])
  const [maxAssignments, setMaxAssignments] = useState<string>('')

  useEffect(() => {
    if (mentor) {
      setName(mentor.name || '')
      setStatus(mentor.status as 'INVITED' | 'ACTIVE' | 'SUSPENDED')
      setExpertiseTags(mentor.expertiseTags || [])
      setMaxAssignments(mentor.maxAssignments?.toString() || '')
    }
  }, [mentor])

  const handleSave = async () => {
    try {
      await updateUser.mutateAsync({
        id: mentorId,
        name: name || null,
        status,
        expertiseTags,
        maxAssignments: maxAssignments ? parseInt(maxAssignments) : null,
      })
      toast.success('Mentor updated successfully')
      refetch()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to update mentor')
    }
  }

  const handleSendInvitation = async () => {
    try {
      await sendInvitation.mutateAsync({ userId: mentorId })
      toast.success('Invitation email sent successfully')
      refetch()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to send invitation')
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center gap-4">
          <Skeleton className="h-9 w-32" />
        </div>
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-48" />
            <Skeleton className="h-4 w-72" />
          </CardHeader>
          <CardContent className="space-y-4">
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
            <Skeleton className="h-10 w-full" />
          </CardContent>
        </Card>
      </div>
    )
  }

  if (!mentor) {
    return (
      <div className="space-y-6">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Mentor not found</AlertTitle>
          <AlertDescription>
            The mentor you&apos;re looking for does not exist.
          </AlertDescription>
        </Alert>
        <Button asChild>
          <Link href={"/admin/mentors" as Route}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Mentors
          </Link>
        </Button>
      </div>
    )
  }

  const statusColors: Record<string, 'default' | 'success' | 'secondary' | 'destructive'> = {
    ACTIVE: 'success',
    INVITED: 'secondary',
    SUSPENDED: 'destructive',
  }

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

      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            {mentor.name || 'Unnamed Mentor'}
          </h1>
          <p className="text-muted-foreground">{mentor.email}</p>
        </div>
        <div className="flex items-center gap-2">
          <Badge variant={statusColors[mentor.status] || 'secondary'} className="text-sm">
            {mentor.status}
          </Badge>
          {mentor.status === 'INVITED' && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleSendInvitation}
              disabled={sendInvitation.isPending}
            >
              {sendInvitation.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Mail className="mr-2 h-4 w-4" />
              )}
              Send Invitation
            </Button>
          )}
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Profile Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5" />
              Profile Information
            </CardTitle>
            <CardDescription>
              Update the mentor&apos;s profile and settings
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" value={mentor.email} disabled />
            </div>

            <div className="space-y-2">
              <Label htmlFor="name">Name</Label>
              <Input
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Enter name"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select value={status} onValueChange={(v) => setStatus(v as typeof status)}>
                <SelectTrigger id="status">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="INVITED">Invited</SelectItem>
                  <SelectItem value="ACTIVE">Active</SelectItem>
                  <SelectItem value="SUSPENDED">Suspended</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Expertise & Capacity */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <GraduationCap className="h-5 w-5" />
              Expertise & Capacity
            </CardTitle>
            <CardDescription>
              Configure expertise areas and assignment limits
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label>Expertise Tags</Label>
              <TagInput
                value={expertiseTags}
                onChange={setExpertiseTags}
                placeholder="Select expertise tags..."
                maxTags={15}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="maxAssignments">Max Assignments</Label>
              <Input
                id="maxAssignments"
                type="number"
                min="1"
                max="100"
                value={maxAssignments}
                onChange={(e) => setMaxAssignments(e.target.value)}
                placeholder="Unlimited"
              />
              <p className="text-xs text-muted-foreground">
                Maximum number of projects this mentor can be assigned
              </p>
            </div>

            {mentor._count && (
              <div className="pt-4 border-t">
                <h4 className="font-medium mb-2">Statistics</h4>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <p className="text-muted-foreground">Total Assignments</p>
                    <p className="text-2xl font-semibold">{mentor._count.assignments}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">Last Login</p>
                    <p className="text-lg">
                      {mentor.lastLoginAt
                        ? new Date(mentor.lastLoginAt).toLocaleDateString()
                        : 'Never'}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Save Button */}
      <div className="flex justify-end gap-4">
        <Button variant="outline" asChild>
          <Link href={"/admin/mentors" as Route}>Cancel</Link>
        </Button>
        <Button onClick={handleSave} disabled={updateUser.isPending}>
          {updateUser.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Save className="mr-2 h-4 w-4" />
          )}
          Save Changes
        </Button>
      </div>

      {/* Assigned Projects */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <ClipboardList className="h-5 w-5" />
            Assigned Projects
          </CardTitle>
          <CardDescription>
            Projects currently assigned to this mentor
          </CardDescription>
        </CardHeader>
        <CardContent>
          {assignmentsData && assignmentsData.assignments.length > 0 ? (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Project</TableHead>
                  <TableHead>Team</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Assigned</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {assignmentsData.assignments.map((assignment) => (
                  <TableRow key={assignment.id}>
                    <TableCell>
                      <Link
                        href={`/admin/projects/${assignment.project.id}`}
                        className="font-medium text-primary hover:underline"
                      >
                        {assignment.project.title}
                      </Link>
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {assignment.project.teamName || '-'}
                    </TableCell>
                    <TableCell>
                      {assignment.project.competitionCategory ? (
                        <Badge variant="outline" className="text-xs">
                          {assignment.project.competitionCategory}
                        </Badge>
                      ) : (
                        <span className="text-muted-foreground">-</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className="text-xs">
                        {assignment.project.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {new Date(assignment.assignedAt).toLocaleDateString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          ) : (
            <p className="py-8 text-center text-muted-foreground">
              No projects assigned to this mentor yet.
            </p>
          )}
        </CardContent>
      </Card>

      {/* Invitation Status */}
      {mentor.status === 'INVITED' && (
        <Alert>
          <Mail className="h-4 w-4" />
          <AlertTitle>Invitation Pending</AlertTitle>
          <AlertDescription>
            This mentor hasn&apos;t accepted their invitation yet. You can resend
            the invitation email using the button above.
          </AlertDescription>
        </Alert>
      )}
    </div>
  )
}
