"use client"

import Link from "next/link"
import { memo, useState, useTransition } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"

import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { BookOpen, Building2, Inbox, CalendarDays, User, PlusCircle, PenTool, Mail, School } from "lucide-react"

import type { StudentEnrolledClass } from "@/modules/classes/types"
import { joinClassByInvitationCodeAction } from "@/modules/classes/actions"

const ClassCard = memo(function ClassCard({ c }: { c: StudentEnrolledClass }) {
  const t = useTranslations("student")
  return (
    <Card className="flex flex-col overflow-hidden transition-all hover:shadow-md">
      <CardHeader className="bg-muted/30 pb-4">
        <div className="flex items-start justify-between gap-4">
          <div className="space-y-1">
            <CardTitle className="line-clamp-1 text-lg">
              <Link href={`/student/learning/courses/${encodeURIComponent(c.id)}`} className="hover:underline">
                {c.name}
              </Link>
            </CardTitle>
            <CardDescription className="flex items-center gap-2 text-xs">
              <span className="flex items-center gap-1">
                <BookOpen className="h-3 w-3" />
                {t("coursesView.grade", { grade: c.grade })}
              </span>
              {c.homeroom && (
                <>
                  <span aria-hidden="true">•</span>
                  <span>{c.homeroom}</span>
                </>
              )}
            </CardDescription>
          </div>
          <Badge variant="secondary" className="shrink-0">
            {t("coursesView.active")}
          </Badge>
        </div>
      </CardHeader>

      <CardContent className="flex-1 space-y-4 py-4">
        <div className="space-y-2 text-sm">
          {c.schoolName && (
            <div className="flex items-center gap-2 text-muted-foreground">
              <School className="h-4 w-4" />
              <span>{c.schoolName}</span>
            </div>
          )}
          {c.teacherName && (
            <div className="flex items-center gap-2 text-muted-foreground">
              <User className="h-4 w-4" />
              <span>{c.teacherName}</span>
            </div>
          )}
          {c.teacherEmail && (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Mail className="h-4 w-4" />
              <a href={`mailto:${c.teacherEmail}`} className="hover:underline hover:text-foreground">
                {c.teacherEmail}
              </a>
            </div>
          )}
          {c.room && (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Building2 className="h-4 w-4" />
              <span>{t("coursesView.room", { room: c.room })}</span>
            </div>
          )}
        </div>
      </CardContent>

      <CardFooter className="flex gap-2 border-t bg-muted/10 p-4">
        <Button asChild variant="outline" size="sm" className="flex-1">
          <Link href={`/student/learning/courses/${encodeURIComponent(c.id)}`}>
            <BookOpen className="mr-2 h-4 w-4" />
            {t("coursesView.details")}
          </Link>
        </Button>
        <Button asChild variant="outline" size="sm" className="flex-1">
          <Link href={`/student/schedule?classId=${encodeURIComponent(c.id)}`}>
            <CalendarDays className="mr-2 h-4 w-4" />
            {t("coursesView.schedule")}
          </Link>
        </Button>
        <Button asChild size="sm" className="flex-1">
          <Link href="/student/learning/assignments">
            <PenTool className="mr-2 h-4 w-4" />
            {t("coursesView.assignments")}
          </Link>
        </Button>
      </CardFooter>
    </Card>
  )
})

export function StudentCoursesView({
  classes,
}: {
  classes: StudentEnrolledClass[]
}) {
  const t = useTranslations("student")
  const router = useRouter()
  const [code, setCode] = useState("")
  const [isPending, startTransition] = useTransition()

  const handleJoin = async (formData: FormData) => {
    startTransition(async () => {
      try {
        const res = await joinClassByInvitationCodeAction(null, formData)
        if (res.success) {
          toast.success(res.message || t("coursesView.joinedSuccess"))
          setCode("")
          router.refresh()
        } else {
          toast.error(res.message || t("coursesView.joinFailed"))
        }
      } catch (err) {
        console.error("[joinClass] failed:", err)
        toast.error(t("coursesView.joinFailed"))
      }
    })
  }

  return (
    <div className="space-y-8">
      {classes.length > 0 && (
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {classes.map((c) => (
            <ClassCard key={c.id} c={c} />
          ))}
        </div>
      )}

      {classes.length === 0 && (
        <EmptyState
          icon={Inbox}
          title={t("coursesView.noCourses")}
          description={t("coursesView.noCoursesDesc")}
          className="py-12"
        />
      )}

      {/* 加入班级表单：无课程时置顶，有课程时置底 */}
      <div className={classes.length === 0 ? "" : "rounded-lg border bg-card p-6 shadow-sm"}>
        <div className={classes.length === 0 ? "rounded-lg border bg-card p-6 shadow-sm" : "mb-6 flex items-center gap-3"}>
          <div className={classes.length === 0 ? "mb-6 flex items-center gap-3" : ""}>
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
              <PlusCircle className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h3 className="text-lg font-semibold">{t("coursesView.joinClass")}</h3>
              <p className="text-sm text-muted-foreground">
                {t("coursesView.joinClassDesc")}
              </p>
            </div>
          </div>
        </div>

        <form action={handleJoin} className="flex flex-col gap-4 sm:flex-row sm:items-end">
          <div className="flex-1 space-y-2">
            <Label htmlFor="join-invitation-code">{t("coursesView.invitationCode")}</Label>
            <Input
              id="join-invitation-code"
              name="code"
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder={t("coursesView.invitationCodePlaceholder")}
              value={code}
              onChange={(e) => setCode(e.target.value)}
              maxLength={6}
              pattern="\d{6}"
              className="max-w-md font-mono tracking-widest"
              required
            />
          </div>
          <Button type="submit" disabled={isPending} size="lg">
            {isPending ? t("coursesView.joining") : t("coursesView.joinButton")}
          </Button>
        </form>
      </div>
    </div>
  )
}
