'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
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 { Badge } from '@/components/ui/badge'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
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 { UserActivityLog } from '@/components/shared/user-activity-log'
import {
  ArrowLeft,
  Save,
  Mail,
  User,
  Shield,
  Loader2,
  AlertCircle,
} from 'lucide-react'

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

  const { data: user, isLoading, refetch } = trpc.user.get.useQuery({ id: userId })
  const updateUser = trpc.user.update.useMutation()
  const sendInvitation = trpc.user.sendInvitation.useMutation()

  // Mentor assignments (only fetched for mentors)
  const { data: mentorAssignments } = trpc.mentor.listAssignments.useQuery(
    { mentorId: userId, page: 1, perPage: 50 },
    { enabled: user?.role === 'MENTOR' }
  )

  const [name, setName] = useState('')
  const [role, setRole] = useState<string>('JURY_MEMBER')
  const [status, setStatus] = useState<string>('INVITED')
  const [expertiseTags, setExpertiseTags] = useState<string[]>([])
  const [maxAssignments, setMaxAssignments] = useState<string>('')

  useEffect(() => {
    if (user) {
      setName(user.name || '')
      setRole(user.role)
      setStatus(user.status)
      setExpertiseTags(user.expertiseTags || [])
      setMaxAssignments(user.maxAssignments?.toString() || '')
    }
  }, [user])

  const handleSave = async () => {
    try {
      await updateUser.mutateAsync({
        id: userId,
        name: name || null,
        role: role as 'JURY_MEMBER' | 'MENTOR' | 'OBSERVER' | 'PROGRAM_ADMIN',
        status: status as 'INVITED' | 'ACTIVE' | 'SUSPENDED',
        expertiseTags,
        maxAssignments: maxAssignments ? parseInt(maxAssignments) : null,
      })
      toast.success('Member updated successfully')
      router.push('/admin/members')
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to update member')
    }
  }

  const handleSendInvitation = async () => {
    try {
      await sendInvitation.mutateAsync({ userId })
      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">
        <Skeleton className="h-9 w-32" />
        <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" />
          </CardContent>
        </Card>
      </div>
    )
  }

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

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

      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">
            {user.name || 'Unnamed Member'}
          </h1>
          <div className="flex items-center gap-2 mt-1">
            <p className="text-muted-foreground">{user.email}</p>
            <Badge variant={user.status === 'ACTIVE' ? 'success' : user.status === 'SUSPENDED' ? 'destructive' : 'secondary'}>
              {user.status}
            </Badge>
          </div>
        </div>
        {user.status === 'INVITED' && (
          <Button
            variant="outline"
            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 className="grid gap-6 md:grid-cols-2">
        {/* Basic Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5" />
              Basic Information
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" value={user.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="role">Role</Label>
              <Select value={role} onValueChange={setRole}>
                <SelectTrigger id="role">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="JURY_MEMBER">Jury Member</SelectItem>
                  <SelectItem value="MENTOR">Mentor</SelectItem>
                  <SelectItem value="OBSERVER">Observer</SelectItem>
                  <SelectItem value="PROGRAM_ADMIN">Program Admin</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select value={status} onValueChange={setStatus}>
                <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">
              <Shield className="h-5 w-5" />
              Expertise & Capacity
            </CardTitle>
          </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"
              />
            </div>
            {user._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">Jury Assignments</p>
                    <p className="text-2xl font-semibold">{user._count.assignments}</p>
                  </div>
                  <div>
                    <p className="text-muted-foreground">Mentor Assignments</p>
                    <p className="text-2xl font-semibold">{user._count.mentorAssignments}</p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Mentor Assignments Section */}
      {user.role === 'MENTOR' && mentorAssignments && mentorAssignments.assignments.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Mentored Projects</CardTitle>
            <CardDescription>
              Projects this mentor is assigned to
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Project</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Assigned</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {mentorAssignments.assignments.map((assignment) => (
                  <TableRow key={assignment.id}>
                    <TableCell>
                      <Link
                        href={`/admin/projects/${assignment.project.id}`}
                        className="font-medium hover:underline"
                      >
                        {assignment.project.title}
                      </Link>
                      {assignment.project.teamName && (
                        <p className="text-sm text-muted-foreground">
                          {assignment.project.teamName}
                        </p>
                      )}
                    </TableCell>
                    <TableCell>
                      {assignment.project.competitionCategory ? (
                        <Badge variant="outline">
                          {assignment.project.competitionCategory.replace('_', ' ')}
                        </Badge>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">
                        {assignment.project.status ?? 'SUBMITTED'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {new Date(assignment.assignedAt).toLocaleDateString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Activity Log */}
      <UserActivityLog userId={userId} />

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

      {/* Save Button */}
      <div className="flex justify-end gap-4">
        <Button variant="outline" asChild>
          <Link href="/admin/members">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>
    </div>
  )
}
