"use client"

import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Search, Eye, Mail, Phone, MapPin, Briefcase } from "lucide-react"
import { adminCandidatesApi, AdminCandidate, AdminCandidateStats } from "@/lib/api"
import { useTranslation } from "@/lib/i18n"

export default function AdminCandidatesPage() {
  const { t } = useTranslation()
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedCandidate, setSelectedCandidate] = useState<AdminCandidate | null>(null)
  const [candidates, setCandidates] = useState<AdminCandidate[]>([])
  const [stats, setStats] = useState<AdminCandidateStats | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)

  useEffect(() => {
    let isMounted = true

    const loadCandidates = async () => {
      setIsLoading(true)
      setErrorMessage(null)
      try {
        const response = await adminCandidatesApi.list()
        if (!isMounted) return
        setCandidates(response.candidates)
        setStats(response.stats)
      } catch (error) {
        if (!isMounted) return
        setErrorMessage(error instanceof Error ? error.message : t("admin.candidates_page.load_error"))
      } finally {
        if (isMounted) {
          setIsLoading(false)
        }
      }
    }

    loadCandidates()

    return () => {
      isMounted = false
    }
  }, [])

  const filteredCandidates = useMemo(() => {
    const term = searchTerm.toLowerCase().trim()
    if (!term) return candidates
    return candidates.filter((candidate) => {
      const name = candidate.name.toLowerCase()
      const email = candidate.email?.toLowerCase() || ""
      return name.includes(term) || email.includes(term)
    })
  }, [candidates, searchTerm])

  return (
    <div className="space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold text-foreground">{t("admin.candidates_page.title")}</h1>
        <p className="text-muted-foreground mt-1">{t("admin.candidates_page.subtitle")}</p>
      </div>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>{t("admin.candidates_page.stats.total")}</CardDescription>
            <CardTitle className="text-3xl">{stats?.totalCandidates ?? 0}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>{t("admin.candidates_page.stats.new")}</CardDescription>
            <CardTitle className="text-3xl">{stats?.newCandidates ?? 0}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>{t("admin.candidates_page.stats.active")}</CardDescription>
            <CardTitle className="text-3xl">{stats?.activeApplications ?? 0}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>{t("admin.candidates_page.stats.hiring_rate")}</CardDescription>
            <CardTitle className="text-3xl">{Math.round(stats?.hiringRate ?? 0)}%</CardTitle>
          </CardHeader>
        </Card>
      </div>

      {/* Search and Table */}
      <Card>
        <CardHeader>
          <div className="flex items-center gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder={t("admin.candidates_page.search_placeholder")}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {errorMessage ? (
            <div className="text-sm text-destructive">{errorMessage}</div>
          ) : null}
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("admin.candidates_page.table.candidate")}</TableHead>
                <TableHead>{t("admin.candidates_page.table.email")}</TableHead>
                <TableHead>{t("admin.candidates_page.table.phone")}</TableHead>
                <TableHead>{t("admin.candidates_page.table.location")}</TableHead>
                <TableHead>{t("admin.candidates_page.table.applications")}</TableHead>
                <TableHead className="text-right">{t("admin.candidates_page.table.actions")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
                    {t("admin.candidates_page.table.loading")}
                  </TableCell>
                </TableRow>
              )}
              {!isLoading && filteredCandidates.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-sm text-muted-foreground">
                    {t("admin.candidates_page.table.empty")}
                  </TableCell>
                </TableRow>
              )}
              {filteredCandidates.map((candidate) => (
                <TableRow key={candidate.id}>
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div>
                        <div className="font-medium">{candidate.name}</div>
                        <div className="text-sm text-muted-foreground">{candidate.title ?? "—"}</div>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{candidate.email ?? "—"}</TableCell>
                  <TableCell>{candidate.phone ?? "—"}</TableCell>
                  <TableCell>{candidate.location ?? "—"}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{candidate.applications.length}</Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <Dialog>
                      <DialogTrigger asChild>
                        <Button variant="ghost" size="icon" onClick={() => setSelectedCandidate(candidate)}>
                          <Eye className="h-4 w-4" />
                        </Button>
                      </DialogTrigger>
                      <DialogContent className="max-w-2xl">
                        <DialogHeader>
                          <DialogTitle>{t("admin.candidates_page.dialog.title")}</DialogTitle>
                          <DialogDescription>
                            {t("admin.candidates_page.dialog.description", { name: candidate.name })}
                          </DialogDescription>
                        </DialogHeader>
                        {selectedCandidate && (
                          <div className="space-y-6">
                            <div className="flex items-start gap-4">
                              <Avatar className="h-20 w-20">
                                <AvatarImage src={selectedCandidate.avatarUrl || "/placeholder.svg"} />
                                <AvatarFallback>
                                  {selectedCandidate.name
                                    .split(" ")
                                    .map((n: string) => n[0])
                                    .join("")}
                                </AvatarFallback>
                              </Avatar>
                              <div className="flex-1">
                                <h3 className="text-xl font-semibold">{selectedCandidate.name}</h3>
                                <p className="text-muted-foreground">{selectedCandidate.title ?? "—"}</p>
                                {selectedCandidate.skills.length > 0 && (
                                  <div className="flex flex-wrap gap-2 mt-3">
                                    {selectedCandidate.skills.map((skill: string) => (
                                      <Badge key={skill} variant="secondary">
                                        {skill}
                                      </Badge>
                                    ))}
                                  </div>
                                )}
                              </div>
                            </div>

                            <div className="grid gap-4">
                              <div className="flex items-center gap-2 text-sm">
                                <Mail className="h-4 w-4 text-muted-foreground" />
                                <span>{selectedCandidate.email ?? "—"}</span>
                              </div>
                              <div className="flex items-center gap-2 text-sm">
                                <Phone className="h-4 w-4 text-muted-foreground" />
                                <span>{selectedCandidate.phone ?? "—"}</span>
                              </div>
                              <div className="flex items-center gap-2 text-sm">
                                <MapPin className="h-4 w-4 text-muted-foreground" />
                                <span>{selectedCandidate.location ?? "—"}</span>
                              </div>
                              <div className="flex items-center gap-2 text-sm">
                                <Briefcase className="h-4 w-4 text-muted-foreground" />
                                <span>{selectedCandidate.experience ?? "—"}</span>
                              </div>
                            </div>

                            <div>
                              <h4 className="font-semibold mb-2">{t("admin.candidates_page.about.title")}</h4>
                              <p className="text-sm text-muted-foreground">
                                {selectedCandidate.bio ?? t("admin.candidates_page.about.empty")}
                              </p>
                            </div>

                            <div>
                              <h4 className="font-semibold mb-2">{t("admin.candidates_page.applications.title")}</h4>
                              <div className="space-y-2">
                                {selectedCandidate.applications.length === 0 && (
                                  <div className="text-sm text-muted-foreground">
                                    {t("admin.candidates_page.applications.empty")}
                                  </div>
                                )}
                                {selectedCandidate.applications.map((app) => (
                                  <div
                                    key={app.id}
                                    className="flex items-center justify-between p-3 border rounded-lg"
                                  >
                                    <div>
                                      <div className="font-medium text-sm">{app.jobTitle}</div>
                                      <div className="text-xs text-muted-foreground">{app.company}</div>
                                    </div>
                                    <Badge
                                      variant={
                                        app.status === "hired"
                                          ? "default"
                                          : app.status === "rejected"
                                            ? "destructive"
                                            : "secondary"
                                      }
                                    >
                                      {app.status === "pending" && t("admin.candidates_page.status.pending")}
                                      {app.status === "reviewed" && t("admin.candidates_page.status.reviewed")}
                                      {app.status === "shortlisted" && t("admin.candidates_page.status.shortlisted")}
                                      {app.status === "hired" && t("admin.candidates_page.status.hired")}
                                      {app.status === "rejected" && t("admin.candidates_page.status.rejected")}
                                    </Badge>
                                  </div>
                                ))}
                              </div>
                            </div>
                          </div>
                        )}
                      </DialogContent>
                    </Dialog>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}
