'use client'

import { useState, useMemo } from 'react'
import Link from 'next/link'
import type { Route } from 'next'
import { trpc } from '@/lib/trpc/client'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Progress } from '@/components/ui/progress'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Users,
  Briefcase,
  ArrowRight,
  Mail,
  MapPin,
  GraduationCap,
  Waves,
  Crown,
  CheckCircle2,
  Circle,
  Clock,
  Search,
} from 'lucide-react'
import { formatDateOnly } from '@/lib/utils'
import { AnimatedCard } from '@/components/shared/animated-container'
import { CountryDisplay } from '@/components/shared/country-display'
import { RecentMessagesCard } from '@/components/mentor/recent-messages-card'

// Status badge colors
const statusColors: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  SUBMITTED: 'secondary',
  ELIGIBLE: 'default',
  ASSIGNED: 'default',
  SEMIFINALIST: 'default',
  FINALIST: 'default',
  REJECTED: 'destructive',
}

// Completion status display
const completionBadge: Record<string, { label: string; variant: 'default' | 'secondary' | 'outline' }> = {
  in_progress: { label: 'In Progress', variant: 'secondary' },
  completed: { label: 'Completed', variant: 'default' },
  paused: { label: 'Paused', variant: 'outline' },
}

function DashboardSkeleton() {
  return (
    <div className="space-y-6">
      <div>
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-4 w-64 mt-2" />
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Skeleton className="h-24" />
        <Skeleton className="h-24" />
        <Skeleton className="h-24" />
      </div>

      <Skeleton className="h-6 w-32" />
      <div className="grid gap-4">
        <Skeleton className="h-40" />
        <Skeleton className="h-40" />
      </div>
    </div>
  )
}

export default function MentorDashboard() {
  const { data: assignments, isLoading } = trpc.mentor.getMyProjects.useQuery()
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')

  const projects = assignments || []
  const completedCount = projects.filter((a) => a.completionStatus === 'completed').length
  const inProgressCount = projects.filter((a) => a.completionStatus === 'in_progress').length

  const filteredProjects = useMemo(() => {
    return projects.filter(a => {
      const matchesSearch = !search ||
        a.project.title.toLowerCase().includes(search.toLowerCase()) ||
        a.project.teamName?.toLowerCase().includes(search.toLowerCase())
      const matchesStatus = statusFilter === 'all' || a.completionStatus === statusFilter
      return matchesSearch && matchesStatus
    })
  }, [projects, search, statusFilter])

  if (isLoading) {
    return <DashboardSkeleton />
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-semibold tracking-tight">
          Mentor Dashboard
        </h1>
        <p className="text-muted-foreground">
          View and manage your assigned mentee projects
        </p>
      </div>

      {/* Recent unread messages from teams */}
      <RecentMessagesCard />

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-3">
        <AnimatedCard index={0}>
          <Card className="border-l-4 border-l-blue-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Assigned Projects</p>
                  <p className="text-2xl font-bold mt-1">{projects.length}</p>
                  <p className="text-xs text-muted-foreground mt-1">Projects you are mentoring</p>
                </div>
                <div className="rounded-xl bg-blue-50 p-3">
                  <Briefcase className="h-5 w-5 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>

        <AnimatedCard index={1}>
          <Card className="border-l-4 border-l-emerald-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Completed</p>
                  <p className="text-2xl font-bold mt-1">{completedCount}</p>
                  <div className="flex items-center gap-2 mt-1">
                    {projects.length > 0 && (
                      <Progress
                        value={(completedCount / projects.length) * 100}
                        className="h-1.5 flex-1"
                        gradient
                      />
                    )}
                    <span className="text-xs text-muted-foreground">
                      {projects.length > 0 ? Math.round((completedCount / projects.length) * 100) : 0}%
                    </span>
                  </div>
                </div>
                <div className="rounded-xl bg-emerald-50 p-3">
                  <CheckCircle2 className="h-5 w-5 text-emerald-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>

        <AnimatedCard index={2}>
          <Card className="border-l-4 border-l-violet-500 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
            <CardContent className="p-5">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Total Team Members</p>
                  <p className="text-2xl font-bold mt-1">
                    {projects.reduce(
                      (acc, a) => acc + (a.project.teamMembers?.length || 0),
                      0
                    )}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">Across all assigned projects</p>
                </div>
                <div className="rounded-xl bg-violet-50 p-3">
                  <Users className="h-5 w-5 text-violet-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </AnimatedCard>
      </div>

      {/* Quick Actions */}
      <div className="flex flex-wrap gap-2">
        <Button variant="outline" size="sm" asChild>
          <Link href={'/mentor/projects' as Route}>
            <Mail className="mr-2 h-4 w-4" />
            Messages
          </Link>
        </Button>
      </div>

      {/* Projects List */}
      <div>
        <h2 className="text-lg font-semibold mb-4">Your Mentees</h2>

        {/* Search and Filter */}
        {projects.length > 0 && (
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center mb-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search projects..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="All statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All statuses</SelectItem>
                <SelectItem value="in_progress">In Progress</SelectItem>
                <SelectItem value="completed">Completed</SelectItem>
                <SelectItem value="paused">Paused</SelectItem>
              </SelectContent>
            </Select>
          </div>
        )}

        {projects.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-12 text-center">
              <div className="rounded-2xl bg-brand-teal/10 p-4">
                <Users className="h-8 w-8 text-brand-teal" />
              </div>
              <p className="mt-4 font-medium">No assigned projects yet</p>
              <p className="text-sm text-muted-foreground mt-1">
                You will see your mentee projects here once they are assigned to
                you.
              </p>
            </CardContent>
          </Card>
        ) : filteredProjects.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-8 text-center">
              <Search className="h-8 w-8 text-muted-foreground/50" />
              <p className="mt-2 text-sm text-muted-foreground">
                No projects match your search criteria
              </p>
              <Button
                variant="ghost"
                size="sm"
                className="mt-2"
                onClick={() => { setSearch(''); setStatusFilter('all') }}
              >
                Clear filters
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4">
            {filteredProjects.map((assignment, index) => {
              const project = assignment.project
              const teamLead = project.teamMembers?.find(
                (m) => m.role === 'LEAD'
              )
              const badge = completionBadge[assignment.completionStatus] || completionBadge.in_progress

              return (
                <AnimatedCard key={assignment.id} index={index}>
                <Card className="transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
                  <CardHeader>
                    <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          <span>
                            {project.program?.year} Edition
                          </span>
                          {project.program && (
                            <>
                              <span>-</span>
                              <span>{project.program.name}</span>
                            </>
                          )}
                        </div>
                        <CardTitle className="flex items-center gap-2 flex-wrap">
                          {project.title}
                          {project.status && (
                            <Badge
                              variant={statusColors[project.status] || 'secondary'}
                            >
                              {project.status.replace('_', ' ')}
                            </Badge>
                          )}
                          <Badge variant={badge.variant}>
                            {assignment.completionStatus === 'completed' && (
                              <CheckCircle2 className="mr-1 h-3 w-3" />
                            )}
                            {assignment.completionStatus === 'in_progress' && (
                              <Circle className="mr-1 h-3 w-3" />
                            )}
                            {assignment.completionStatus === 'paused' && (
                              <Clock className="mr-1 h-3 w-3" />
                            )}
                            {badge.label}
                          </Badge>
                        </CardTitle>
                        {project.teamName && (
                          <CardDescription>{project.teamName}</CardDescription>
                        )}
                      </div>
                      <Button variant="outline" size="sm" asChild>
                        <Link href={`/mentor/projects/${project.id}` as Route}>
                          View Details
                          <ArrowRight className="ml-2 h-4 w-4" />
                        </Link>
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {/* Category badges */}
                    <div className="flex flex-wrap gap-2">
                      {project.competitionCategory && (
                        <Badge variant="outline" className="gap-1">
                          <GraduationCap className="h-3 w-3" />
                          {project.competitionCategory === 'STARTUP'
                            ? 'Start-up'
                            : 'Business Concept'}
                        </Badge>
                      )}
                      {project.oceanIssue && (
                        <Badge variant="outline" className="gap-1">
                          <Waves className="h-3 w-3" />
                          {project.oceanIssue.replace(/_/g, ' ')}
                        </Badge>
                      )}
                      {project.country && (
                        <Badge variant="outline" className="gap-1">
                          <MapPin className="h-3 w-3" />
                          <CountryDisplay country={project.country} />
                        </Badge>
                      )}
                    </div>

                    {/* Description preview */}
                    {project.description && (
                      <p className="text-sm text-muted-foreground line-clamp-2">
                        {project.description}
                      </p>
                    )}

                    {/* Team Lead Info */}
                    {teamLead && (
                      <div className="flex items-center gap-3 pt-2 border-t">
                        <Avatar className="h-8 w-8">
                          <AvatarFallback className="text-xs">
                            <Crown className="h-4 w-4 text-yellow-500" />
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium">
                            {teamLead.user.name || 'Unnamed'}{' '}
                            <span className="text-muted-foreground font-normal">
                              (Team Lead)
                            </span>
                          </p>
                          <a
                            href={`mailto:${teamLead.user.email}`}
                            className="text-xs text-muted-foreground hover:text-primary flex items-center gap-1"
                          >
                            <Mail className="h-3 w-3" />
                            {teamLead.user.email}
                          </a>
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {project.teamMembers?.length || 0} team member
                          {(project.teamMembers?.length || 0) !== 1 ? 's' : ''}
                        </div>
                      </div>
                    )}

                    {/* Assignment date + last viewed */}
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>Assigned {formatDateOnly(assignment.assignedAt)}</span>
                      {assignment.lastViewedAt && (
                        <span>Last viewed {formatDateOnly(assignment.lastViewedAt)}</span>
                      )}
                    </div>
                  </CardContent>
                </Card>
                </AnimatedCard>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}
