"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 { 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 } from "lucide-react"
import { adminJobsApi, transformApiJobToFrontend, type AdminJob } from "@/lib/api"

type AdminJobRow = ReturnType<typeof transformApiJobToFrontend> & {
  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<Partial<AdminJob>>({})
  const [isLoading, setIsLoading] = useState(true)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)

  useEffect(() => {
    const loadJobs = async () => {
      try {
        setIsLoading(true)
        setErrorMessage(null)
        const jobsData = await adminJobsApi.list({ limit: 100 })
        setJobs(jobsData.data ?? [])
      } catch (error) {
        console.error("Failed to load jobs:", error)
        setErrorMessage("Unable to load jobs right now.")
        setJobs([])
      } finally {
        setIsLoading(false)
      }
    }

    loadJobs()
  }, [])

  const jobRows = useMemo<AdminJobRow[]>(
    () =>
      jobs.map((job) => {
        const mapped = transformApiJobToFrontend(job)
        const applicationsCount =
          typeof (job as { applicationsCount?: number }).applicationsCount === "number"
            ? (job as { applicationsCount?: number }).applicationsCount
            : 0
        return {
          ...mapped,
          status: job.status,
          applicationsCount,
        }
      }),
    [jobs],
  )

  const companyOptions = useMemo(
    () => Array.from(new Set(jobRows.map((job) => job.company))).sort(),
    [jobRows],
  )

  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)
    // Find original admin job to populate edit form correctly if needed, or just use row data
    // Converting row data back to partial AdminJob for editing
    setEditForm({
      title: job.title,
      description: job.description,
      // Add other fields as necessary
    })
    setIsEditDialogOpen(true)
  }

  const handleDeleteJob = async (idStr: string) => {
    if (!confirm("Are you sure you want to delete this job?")) return

    const id = parseInt(idStr)
    if (isNaN(id)) return

    try {
      await adminJobsApi.delete(id)
      setJobs((prevJobs) => prevJobs.filter((job) => job.id !== id))
    } catch (error) {
      console.error("Failed to delete job:", error)
      alert("Failed to delete job")
    }
  }

  const handleSaveEdit = async () => {
    if (!selectedJob) return
    const id = parseInt(selectedJob.id)
    if (isNaN(id)) return

    try {
      setIsLoading(true)
      const updated = await adminJobsApi.update(id, editForm)
      setJobs((prev) => prev.map((j) => (j.id === id ? updated : j)))
      setIsEditDialogOpen(false)
    } catch (error) {
      console.error("Failed to update job:", error)
      alert("Failed to update job")
    } finally {
      setIsLoading(false)
    }
  }

  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>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              New job
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Create new job</DialogTitle>
              <DialogDescription>Fill in the details for the new job opening</DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid gap-2">
                <Label htmlFor="title">Job title</Label>
                <Input id="title" placeholder="e.g. Full Stack Developer" />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="company">Company</Label>
                <Select>
                  <SelectTrigger id="company">
                    <SelectValue placeholder="Select a company" />
                  </SelectTrigger>
                  <SelectContent>
                    {companyOptions.map((company) => (
                      <SelectItem key={company} value={company}>
                        {company}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="location">Location</Label>
                  <Input id="location" placeholder="São Paulo, SP" />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="type">Type</Label>
                  <Select>
                    <SelectTrigger>
                      <SelectValue placeholder="Select" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="full-time">Full time</SelectItem>
                      <SelectItem value="part-time">Part time</SelectItem>
                      <SelectItem value="contract">Contract</SelectItem>
                      <SelectItem value="remote">Remote</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="salary">Salary</Label>
                  <Input id="salary" placeholder="R$ 8,000 - R$ 12,000" />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="level">Level</Label>
                  <Select>
                    <SelectTrigger>
                      <SelectValue placeholder="Select" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="junior">Junior</SelectItem>
                      <SelectItem value="mid">Mid-level</SelectItem>
                      <SelectItem value="senior">Senior</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  placeholder="Describe the responsibilities and requirements..."
                  rows={4}
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                Cancel
              </Button>
              <Button onClick={() => setIsCreateDialogOpen(false)}>Publish job</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 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>
                  <div>
                    <Label className="text-muted-foreground">Location</Label>
                    <p className="font-medium">{selectedJob.location}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">Type</Label>
                    <p><Badge variant="outline">{selectedJob.type}</Badge></p>
                  </div>
                  <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 className="grid gap-2">
                <Label htmlFor="edit-description">Description</Label>
                <Textarea
                  id="edit-description"
                  rows={4}
                  value={editForm.description || ""}
                  onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                />
              </div>
              {/* Add more fields as needed for full editing capability */}
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>Cancel</Button>
              <Button onClick={handleSaveEdit}>Save Changes</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* 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>
                <TableHead>Location</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Applications</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground">
                    Loading jobs...
                  </TableCell>
                </TableRow>
              ) : errorMessage ? (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-destructive">
                    {errorMessage}
                  </TableCell>
                </TableRow>
              ) : filteredJobs.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={7} 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>
                    <TableCell>{job.location}</TableCell>
                    <TableCell>
                      <Badge variant="secondary">{job.type}</Badge>
                    </TableCell>
                    <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>
        </CardContent>
      </Card>
    </div>
  )
}
