"use client"

import Link from "next/link"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import {
  Plus,
  RefreshCw,
  Copy,
  Users,
  MapPin,
  GraduationCap,
} from "lucide-react"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn } from "@/shared/lib/utils"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
import type { TeacherClass } from "../types"
import {
  ensureClassInvitationCodeAction,
  regenerateClassInvitationCodeAction,
  joinClassByInvitationCodeAction,
} from "../actions"

const getSeededValue = (seed: string, index: number) => {
  let h = 2166136261
  const str = `${seed}:${index}`
  for (let i = 0; i < str.length; i += 1) {
    h ^= str.charCodeAt(i)
    h = Math.imul(h, 16777619)
  }
  return (h >>> 0) / 4294967296
}

export function MyClassesGrid({
  classes,
  subjectOptions,
}: {
  classes: TeacherClass[]
  subjectOptions: string[]
}) {
  const router = useRouter()
  const t = useTranslations("classes")
  const [isWorking, setIsWorking] = useState(false)
  const [joinOpen, setJoinOpen] = useState(false)
  const [joinSubject, setJoinSubject] = useState("")

  const handleJoin = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      const res = await joinClassByInvitationCodeAction(null, formData)
      if (res.success) {
        toast.success(res.message || t("invitation.joinSuccess"))
        setJoinOpen(false)
        setJoinSubject("")
        router.refresh()
      } else {
        toast.error(res.message || t("invitation.joinFailed"))
      }
    } catch {
      toast.error(t("invitation.joinFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Filter Bar */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-end">
        <div className="relative">
          <Dialog
            open={joinOpen}
            onOpenChange={(open) => {
              if (isWorking) return
              setJoinOpen(open)
              if (!open) setJoinSubject("")
            }}
          >
            <DialogTrigger asChild>
              <div className="group relative">
                {/* Decorative Ticket Stub Effect */}
                <div className="absolute -inset-0.5 bg-gradient-to-r from-primary/20 to-secondary/20 rounded-lg blur opacity-30 group-hover:opacity-60 transition duration-500"></div>
                <Button className="relative gap-2 h-10 px-5 shadow-sm border border-primary/10 hover:shadow-md transition-all bg-background text-foreground hover:bg-muted/50" disabled={isWorking} variant="outline">
                  <div className="flex items-center justify-center w-5 h-5 rounded-full bg-primary/10 text-primary group-hover:scale-110 transition-transform duration-300">
                    <Plus className="size-3.5" strokeWidth={3} />
                  </div>
                  <span className="font-semibold tracking-tight">{t("myClasses.joinNew")}</span>
                </Button>
              </div>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[480px] p-0 overflow-hidden gap-0 border-none shadow-2xl">
              {/* Header with Pattern */}
              <div className="relative bg-primary/5 p-6 border-b border-border/50">
                <div className="absolute inset-0 opacity-[0.03]" style={{ backgroundImage: 'radial-gradient(#000 1px, transparent 1px)', backgroundSize: '12px 12px' }}></div>
                <DialogHeader className="relative z-10">
                  <DialogTitle className="text-xl font-bold flex items-center gap-2">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm">
                      <Plus className="size-5" />
                    </div>
                    {t("myClasses.joinTitle")}
                  </DialogTitle>
                  <DialogDescription className="text-muted-foreground mt-1.5">
                    {t("myClasses.joinDescription")}
                  </DialogDescription>
                </DialogHeader>
              </div>

              <form action={handleJoin} className="bg-card">
                <div className="p-6 space-y-6">
                  <div className="space-y-3">
                    <Label htmlFor="join-code" className="text-sm font-medium">
                      {t("myClasses.invitationCode")}
                    </Label>
                    <div className="relative">
                      <Input
                        id="join-code"
                        name="code"
                        className="h-12 text-center text-2xl font-mono tracking-[0.5em] font-bold uppercase placeholder:tracking-normal placeholder:font-sans placeholder:text-base placeholder:font-normal"
                        placeholder={t("myClasses.invitationCodePlaceholder")}
                        required
                        maxLength={6}
                        pattern="\d{6}"
                        autoComplete="off"
                        autoFocus
                      />
                      <div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground/30 pointer-events-none">
                        <Users className="size-5" />
                      </div>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t("myClasses.invitationCodeHint")}
                    </p>
                  </div>
                  <div className="space-y-3">
                    <Label htmlFor="join-subject" className="text-sm font-medium">
                      {t("myClasses.subject")}
                    </Label>
                    <Select value={joinSubject} onValueChange={(v) => setJoinSubject(v)}>
                      <SelectTrigger id="join-subject" className="h-12">
                        <SelectValue placeholder={subjectOptions.length === 0 ? t("myClasses.noSubjects") : t("myClasses.selectSubject")} />
                      </SelectTrigger>
                      <SelectContent>
                        {subjectOptions.map((subject) => (
                          <SelectItem key={subject} value={subject}>
                            {subject}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <input type="hidden" name="subject" value={joinSubject} />
                  </div>
                </div>
                <DialogFooter className="p-6 pt-2 bg-muted/5 border-t border-border/50">
                  <Button type="button" variant="ghost" onClick={() => setJoinOpen(false)} disabled={isWorking}>
                    {t("myClasses.cancel")}
                  </Button>
                  <Button type="submit" disabled={isWorking || !joinSubject || subjectOptions.length === 0} className="min-w-[100px]">
                    {isWorking ? t("myClasses.joining") : t("myClasses.join")}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* List */}
      <div className="flex flex-col gap-4">
        {classes.length === 0 ? (
          <EmptyState
            title={t("myClasses.empty.title")}
            description={t("myClasses.empty.description")}
            icon={Users}
            action={{ label: t("myClasses.join"), onClick: () => setJoinOpen(true) }}
            className="h-[360px] bg-card border-dashed"
          />
        ) : (
          classes.map((c) => (
            <ClassTicket key={c.id} c={c} onWorkingChange={setIsWorking} />
          ))
        )}
      </div>
    </div>
  )
}

import { ClassScheduleGrid } from "./class-detail/class-schedule-widget"
import { ClassTrendsWidget } from "./class-detail/class-trends-widget"

// Removed MiniSchedule since we're using ClassScheduleGrid now

function ClassTicket({
  c,
  onWorkingChange,
}: {
  c: TeacherClass
  onWorkingChange: (v: boolean) => void
}) {
  const router = useRouter()
  const t = useTranslations("classes")

  const handleEnsureCode = async (): Promise<void> => {
    onWorkingChange(true)
    try {
      const res = await ensureClassInvitationCodeAction(c.id)
      if (res.success) {
        toast.success(res.message || t("invitation.generateSuccess"))
        router.refresh()
      } else {
        toast.error(res.message || t("invitation.generateFailed"))
      }
    } catch {
      toast.error(t("invitation.generateFailed"))
    } finally {
      onWorkingChange(false)
    }
  }

  const handleRegenerateCode = async (): Promise<void> => {
    onWorkingChange(true)
    try {
      const res = await regenerateClassInvitationCodeAction(c.id)
      if (res.success) {
        toast.success(res.message || t("invitation.regenerateSuccess"))
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedRegenerate"))
      }
    } catch {
      toast.error(t("list.failedRegenerate"))
    } finally {
      onWorkingChange(false)
    }
  }

  const handleCopyCode = async (): Promise<void> => {
    const code = c.invitationCode ?? ""
    if (!code) return
    try {
      await navigator.clipboard.writeText(code)
      toast.success(t("myClasses.codeCopied"))
    } catch {
      toast.error(t("list.failedCopy"))
    }
  }

  // Real data for chart
  const recentAssignments = c.recentAssignments ?? []
  
  // Calculate performance change for indicator (still needed for the top indicator)
  // We can't reuse chart data easily here without recalculating, but ClassTrendsWidget handles its own data now
  const lastTwoAssignments = [...recentAssignments].reverse().slice(-2)
  const performanceChange = lastTwoAssignments.length === 2 && lastTwoAssignments[0].submittedCount > 0
    ? ((lastTwoAssignments[1].submittedCount - lastTwoAssignments[0].submittedCount) / lastTwoAssignments[0].submittedCount) * 100
    : 0
  const isPositive = performanceChange >= 0

  return (
    <div className="group relative flex w-full overflow-hidden rounded-xl border bg-card shadow-sm transition-all hover:shadow-md">
      {/* Realistic Paper Texture & Noise */}
      <div className="absolute inset-0 pointer-events-none opacity-[0.02]" style={{ backgroundImage: 'url("data:image/svg+xml,%3Csvg viewBox=\'0 0 200 200\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cfilter id=\'noiseFilter\'%3E%3CfeTurbulence type=\'fractalNoise\' baseFrequency=\'0.65\' numOctaves=\'3\' stitchTiles=\'stitch\'/%3E%3C/filter%3E%3Crect width=\'100%25\' height=\'100%25\' filter=\'url(%23noiseFilter)\'/%3E%3C/svg%3E")' }}></div>
      <div className="absolute inset-0 pointer-events-none opacity-[0.03]" style={{ backgroundImage: 'radial-gradient(#000 1px, transparent 1px)', backgroundSize: '16px 16px' }}></div>

      {/* Decorative Barcode Strip */}
      <div className="absolute left-0 top-0 bottom-0 w-1.5 bg-primary/10 flex flex-col justify-between py-2 pointer-events-none">
        {Array.from({ length: 20 }).map((_, i) => (
          <div
            key={i}
            className="w-full h-px bg-primary/20"
            style={{ marginBottom: `${2 + getSeededValue(c.id, i) * 8}px` }}
          ></div>
        ))}
      </div>

      {/* Left Section: Basic Info (Narrower) */}
      <div className="flex w-full flex-col justify-between p-5 pl-7 sm:w-[320px] sm:flex-shrink-0 relative z-10 border-r border-dashed border-muted-foreground/20">
        {/* Punch Hole Effect Top-Left */}
        <div className="absolute -left-2 -top-2 h-6 w-6 rounded-full bg-background border border-border shadow-[inset_1px_1px_2px_rgba(0,0,0,0.1)] z-20"></div>

        <div className="flex flex-col gap-4">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/5 text-xl font-bold text-primary shadow-sm border border-primary/10">
              {c.grade.replace(/[^0-9]/g, '')}
            </div>
            <div className="flex flex-col">
              <Link href={`/teacher/classes/my/${encodeURIComponent(c.id)}`} className="text-lg font-bold hover:underline tracking-tight line-clamp-1">
                {c.name}
              </Link>
              <Badge variant="secondary" className="w-fit font-normal text-xs bg-muted/50 font-mono tracking-tight">
                {c.grade} • {c.id.slice(-4).toUpperCase()}
              </Badge>
            </div>
          </div>
          
          <div className="space-y-2 text-sm text-muted-foreground">
            <div className="flex items-center gap-2">
              <Users className="size-4 text-muted-foreground/70" />
              <span className="font-medium text-foreground/80">{c.studentCount}</span> {t("myClasses.students")}
            </div>
            <div className="flex items-center gap-2">
              <MapPin className="size-4 text-muted-foreground/70" />
              <span className="font-medium text-foreground/80">{c.room || t("myClasses.noRoom")}</span>
            </div>
            {c.schoolName && (
              <div className="flex items-center gap-2">
                <GraduationCap className="size-4 text-muted-foreground/70" />
                <span className="line-clamp-1">{c.schoolName}</span>
              </div>
            )}
          </div>
        </div>

        {/* Invitation Code Section */}
        <div className="mt-6 pt-4 border-t border-dashed border-border relative">
           {/* Tiny Cut marks */}
           <div className="absolute -left-5 top-[-1px] w-2 h-[2px] bg-border"></div>
           <div className="absolute -right-5 top-[-1px] w-2 h-[2px] bg-border"></div>

           <div className="flex flex-col gap-1.5">
             <div className="flex items-center justify-between">
               <span className="text-[10px] uppercase text-muted-foreground font-semibold tracking-wider">{t("myClasses.entryPass")}</span>
               <div className="flex gap-0.5">
                 {Array.from({ length: 5 }).map((_, i) => (
                   <div key={i} className="w-0.5 h-2 bg-muted-foreground/20"></div>
                 ))}
               </div>
             </div>
             <div className="flex items-center justify-between gap-2 bg-muted/30 px-3 py-1.5 rounded-sm border border-dashed border-muted-foreground/30 relative overflow-hidden">
               <span className="font-mono text-lg font-bold tracking-widest text-foreground z-10">{c.invitationCode || "—"}</span>
               
               {/* Faint QR Code Placeholder Background */}
               <div className="absolute right-10 top-1/2 -translate-y-1/2 opacity-[0.03]">
                 <div className="w-8 h-8 bg-current grid grid-cols-4 grid-rows-4 gap-px">
                   {Array.from({ length: 16 }).map((_, i) => (
                    <div key={i} className={cn("bg-transparent", getSeededValue(`${c.id}-qr`, i) > 0.5 && "bg-black")}></div>
                   ))}
                 </div>
               </div>

               {c.invitationCode ? (
                  <div className="flex gap-1 z-10">
                    <Button variant="ghost" size="icon" className="h-7 w-7 hover:bg-muted" onClick={handleCopyCode} title={t("myClasses.copyCode")}>
                      <Copy className="size-3.5" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-7 w-7 hover:bg-muted" onClick={handleRegenerateCode} title={t("myClasses.regenerateCode")}>
                      <RefreshCw className="size-3.5" />
                    </Button>
                  </div>
               ) : (
                  <Button variant="outline" size="sm" className="h-7 text-xs z-10" onClick={handleEnsureCode}>
                    {t("invitation.generate")}
                  </Button>
               )}
             </div>
           </div>
        </div>
      </div>

      {/* Dashed Divider (Ticket perforation) */}
      <div className="relative hidden w-4 flex-col items-center justify-center sm:flex -ml-2 z-20">
         <div className="absolute -top-2 h-4 w-4 rounded-full bg-background border border-border shadow-[inset_0_-1px_1px_rgba(0,0,0,0.05)]" />
         <div className="h-full w-px border-l-2 border-dashed border-muted-foreground/20 relative">
            {/* Scissor Icon */}
            <div className="absolute top-1/2 -left-[5px] -translate-y-1/2 text-muted-foreground/20 -rotate-90 text-[10px]">✂</div>
         </div>
         <div className="absolute -bottom-2 h-4 w-4 rounded-full bg-background border border-border shadow-[inset_0_1px_1px_rgba(0,0,0,0.05)]" />
      </div>

      {/* Right Section: Stats & Actions (Wider) */}
      <div className="flex flex-1 flex-col bg-muted/5 p-6 relative z-10">
        <div className="flex flex-1 gap-6">
           {/* Left: Submission Trends */}
           <div className="flex-1 flex flex-col gap-4 min-w-0">
              <div className="flex items-center justify-between">
                 <h4 className="text-sm font-semibold text-foreground/80">{t("myClasses.submissionTrends")}</h4>
                 <span className={cn(
                   "text-xs font-bold px-2 py-0.5 rounded-full border flex items-center gap-1",
                   isPositive 
                     ? "text-emerald-600 bg-emerald-50 border-emerald-100" 
                     : "text-red-600 bg-red-50 border-red-100"
                 )}>
                   {isPositive ? "+" : ""}{Math.round(performanceChange)}% <span className={cn("font-normal opacity-70 hidden sm:inline")}>{t("myClasses.vsLastWeek")}</span>
                 </span>
              </div>
              
              {/* Real Chart */}
              <div className="h-[140px] w-full">
                <ClassTrendsWidget assignments={recentAssignments} compact className="h-full w-full" />
              </div>
           </div>

           {/* Right: Weekly Schedule */}
           <div className="flex-1 flex flex-col gap-4 border-l border-dashed border-muted-foreground/20 pl-6 min-w-0">
              <div className="h-[170px] w-full overflow-y-auto pr-1">
                 <ClassScheduleGrid schedule={c.schedule ?? []} compact />
              </div>
           </div>
        </div>
      </div>
    </div>
  )
}
