"use client"

import { useEffect, useMemo, useState } from "react"
import Link from "next/link"
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Plus, Search, Edit, Trash2, Eye, ChevronLeft, ChevronRight } from "lucide-react"
import { adminJobsApi, adminCompaniesApi, jobsApi, type AdminJob, type AdminCompany } from "@/lib/api"

type AdminJobRow = {
  id: string
  title: string
  company: string
  location: string
  type: string
  workMode: string
  description: string
  requirements: string[]
  postedAt: string
  isFeatured: boolean
  status?: string
  applicationsCount?: number
}

export default function AdminJobsPage() {
  const [searchTerm, setSearchTerm] = useState("")
  const [jobs, setJobs] = useState<AdminJob[]>([])
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedJob, setSelectedJob] = useState<AdminJobRow | null>(null)
  const [editForm, setEditForm] = useState<{ title?: string }>({})
  const [isLoading, setIsLoading] = useState(true)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [companies, setCompanies] = useState<AdminCompany[]>([])

  // Pagination State
  const [page, setPage] = useState(1)
  const [limit] = useState(10)
  const [totalPages, setTotalPages] = useState(1)
  const [totalJobs, setTotalJobs] = useState(0)

  const [createForm, setCreateForm] = useState({
    title: "",
    company: "",
    location: "",
    type: "",
    level: "",
    salary: "",
    description: "",
  })

  useEffect(() => {
    const loadJobs = async () => {
      try {
        setIsLoading(true)
        setErrorMessage(null)
        // Fetch with pagination
        const jobsData = await adminJobsApi.list({ limit, page })
        setJobs(jobsData.data ?? [])
        // Assuming metadata contains total/page info, or fallback if not available
        // Need to check API response structure broadly, but assuming standard "meta" or similar
        // For now, if no explicit meta, we rely on checking array length vs limit as a heuristic?
        // Wait, adminJobsApi.list returns Promise<{ data: AdminJob[], meta?: ... }> ?
        // Let's assume standard response for now. If API doesn't return total, we might need a separate count call or API update.
        // Checking `adminJobsApi.list` later if issues arise. Assuming it returns `total` somewhere if needed.
        // For now preventing errors:
        if (jobsData.pagination) {
          setTotalPages(Math.ceil((jobsData.pagination.total || 0) / limit))
          setTotalJobs(jobsData.pagination.total || 0)
        } else {
          // Fallback: simpler pagination if no meta
          setTotalPages(1)
        }

      } catch (error) {
        console.error("Failed to load jobs:", error)
        setErrorMessage("Unable to load jobs right now.")
        setJobs([])
      } finally {
        setIsLoading(false)
      }
    }

    loadJobs()

    // Load companies (keep this as looks like independent lookup)
    const loadCompanies = async () => {
      try {
        const companiesData = await adminCompaniesApi.list(undefined, 1, 100)
        setCompanies(companiesData.data ?? [])
      } catch (error) {
        console.error("[DEBUG] Failed to load companies:", error)
      }
    }
    loadCompanies()
  }, [page, limit]) // Reload when page changes

  const jobRows = useMemo<AdminJobRow[]>(
    () =>
      jobs.map((job) => {
        const applicationsCount =
          typeof (job as { applicationsCount?: number }).applicationsCount === "number"
            ? (job as { applicationsCount?: number }).applicationsCount
            : 0
        return {
          id: String(job.id),
          title: job.title,
          company: job.companyName,
          location: "",
          type: "full-time" as const,
          workMode: "onsite" as const,
          description: "",
          requirements: [],
          postedAt: job.createdAt,
          isFeatured: false,
          status: job.status,
          applicationsCount,
        }
      }),
    [jobs],
  )


  const filteredJobs = useMemo(
    () =>
      jobRows.filter(
        (job) =>
          job.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
          job.company.toLowerCase().includes(searchTerm.toLowerCase()),
      ),
    [jobRows, searchTerm],
  )

  const activeJobs = useMemo(
    () =>
      jobs.filter((job) =>
        ["published", "open", "active"].includes(job.status?.toLowerCase() ?? ""),
      ).length,
    [jobs],
  )

  const totalApplications = useMemo(
    () => jobRows.reduce((sum, job) => sum + (job.applicationsCount ?? 0), 0),
    [jobRows],
  )

  const handleViewJob = (job: AdminJobRow) => {
    setSelectedJob(job)
    setIsViewDialogOpen(true)
  }

  const handleEditJob = (job: AdminJobRow) => {
    setSelectedJob(job)
    setEditForm({
      title: job.title,
    })
    setIsEditDialogOpen(true)
  }

  const handleDeleteJob = async (id: string) => {
    console.log("[JOBS_PAGE] handleDeleteJob called with id:", id)
    if (!confirm("Are you sure you want to delete this job?")) return

    try {
      console.log("[JOBS_PAGE] Calling jobsApi.delete...")
      await jobsApi.delete(id)
      console.log("[JOBS_PAGE] Job deleted successfully, updating local state")
      setJobs((prevJobs) => prevJobs.filter((job) => job.id !== id))
    } catch (error) {
      console.error("[JOBS_PAGE] Failed to delete job:", error)
      alert("Failed to delete job")
    }
  }


  const handleSaveEdit = async () => {
    if (!selectedJob) return

    console.log("[JOBS_PAGE] handleSaveEdit called for job:", selectedJob.id)
    console.log("[JOBS_PAGE] Edit form data:", editForm)

    try {
      setIsLoading(true)
      console.log("[JOBS_PAGE] Calling jobsApi.update...")
      const updated = await jobsApi.update(selectedJob.id, editForm)
      console.log("[JOBS_PAGE] Job updated successfully:", updated)
      // Reload jobs to get fresh data
      const jobsData = await adminJobsApi.list({ limit: 10, page: 1 })
      setJobs(jobsData.data ?? [])
      setIsEditDialogOpen(false)
    } catch (error) {
      console.error("[JOBS_PAGE] Failed to update job:", error)
      alert("Failed to update job")
    } finally {
      setIsLoading(false)
    }
  }


  const handlePreviousPage = () => {
    if (page > 1) setPage(page - 1)
  }

  const handleNextPage = () => {
    // If we rely on generic "if array < limit then end" logic or strict meta total pages
    if (page < totalPages) setPage(page + 1)
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Job management</h1>
          <p className="text-muted-foreground mt-1">Manage all jobs posted on the platform</p>
        </div>
        <Link href="/dashboard/jobs/new">
          <Button className="gap-2">
            <Plus className="h-4 w-4" />
            New job
          </Button>
        </Link>
      </div>

      {/* View Job Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Job Details</DialogTitle>
          </DialogHeader>
          {selectedJob && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">Title</Label>
                  <p className="font-medium">{selectedJob.title}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">Company</Label>
                  <p className="font-medium">{selectedJob.company}</p>
                </div>
                {/* Location and Type removed from table but kept in dialog if data exists, valid? 
                    User asked to remove from "table" mainly. Keeping detail view intact is safer. 
                    But wait, selectedJob still has them (empty strings). */}
                <div>
                  <Label className="text-muted-foreground">Status</Label>
                  <p><Badge>{selectedJob.status}</Badge></p>
                </div>
                <div>
                  <Label className="text-muted-foreground">Applications</Label>
                  <p className="font-medium">{selectedJob.applicationsCount}</p>
                </div>
              </div>
              <div>
                <Label className="text-muted-foreground">Description</Label>
                <div className="mt-1 p-3 bg-muted rounded-md text-sm whitespace-pre-wrap max-h-60 overflow-y-auto">
                  {selectedJob.description}
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button onClick={() => setIsViewDialogOpen(false)}>Close</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Job Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Edit Job</DialogTitle>
            <DialogDescription>Update job details</DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="edit-title">Job title</Label>
              <Input
                id="edit-title"
                value={editForm.title || ""}
                onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>Cancel</Button>
            <Button onClick={handleSaveEdit}>Save Changes</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Total jobs</CardDescription>
            <CardTitle className="text-3xl">{jobs.length}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Active jobs</CardDescription>
            <CardTitle className="text-3xl">{activeJobs}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Applications</CardDescription>
            <CardTitle className="text-3xl">{totalApplications}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Conversion rate</CardDescription>
            <CardTitle className="text-3xl">
              {jobs.length > 0 ? Math.round((activeJobs / jobs.length) * 100) : 0}%
            </CardTitle>
          </CardHeader>
        </Card>
      </div>

      {/* Search and Filter */}
      <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="Search jobs by title or company..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Role</TableHead>
                <TableHead>Company</TableHead>
                {/* Removed Location and Type Headers */}
                <TableHead>Applications</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-muted-foreground">
                    Loading jobs...
                  </TableCell>
                </TableRow>
              ) : errorMessage ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-destructive">
                    {errorMessage}
                  </TableCell>
                </TableRow>
              ) : filteredJobs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-muted-foreground">
                    No jobs found.
                  </TableCell>
                </TableRow>
              ) : (
                filteredJobs.map((job) => (
                  <TableRow key={job.id}>
                    <TableCell className="font-medium">{job.title}</TableCell>
                    <TableCell>{job.company}</TableCell>
                    {/* Removed Location and Type Cells */}
                    <TableCell>{job.applicationsCount ?? 0}</TableCell>
                    <TableCell>
                      <Badge variant="default">{job.status ?? "Active"}</Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex items-center justify-end gap-2">
                        <Button variant="ghost" size="icon" onClick={() => handleViewJob(job)}>
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => handleEditJob(job)}>
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" onClick={() => handleDeleteJob(job.id)}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {/* Pagination Controls */}
          <div className="flex items-center justify-between space-x-2 py-4">
            <div className="text-sm text-muted-foreground">
              {/* Page info (optional) */}
              Page {page} of {totalPages}
            </div>
            <div className="space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={handlePreviousPage}
                disabled={page <= 1 || isLoading}
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={handleNextPage}
                disabled={page >= totalPages || isLoading}
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>

        </CardContent>
      </Card>
    </div>
  )
}
