'use client'

import * as React from 'react'
import Link from 'next/link'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Search,
  Clock,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Eye,
  MapPin,
  Building2,
  Users,
  Calendar,
  DollarSign,
  FileText,
  ThumbsUp,
  ThumbsDown,
  ArrowRight,
  Filter,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { requisitions, countries, currentUser } from '@/lib/mock-data'
import { STATUS_CONFIG, URGENCY_CONFIG, type Requisition } from '@/lib/types'
import { toast } from 'sonner'

function getInitials(name: string): string {
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
}

function getDaysUntilDeadline(deadline: string): number {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  return Math.ceil((deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
}

function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleDateString('es-ES', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  })
}

function getDaysSinceCreated(dateString: string): number {
  const now = new Date()
  const created = new Date(dateString)
  return Math.ceil((now.getTime() - created.getTime()) / (1000 * 60 * 60 * 24))
}

interface ApprovalCardProps {
  requisition: Requisition
  approvalType: 'rrhh' | 'admin'
  onApprove: (req: Requisition) => void
  onReject: (req: Requisition) => void
  onView: (req: Requisition) => void
}

function ApprovalCard({ requisition, approvalType, onApprove, onReject, onView }: ApprovalCardProps) {
  const urgency = URGENCY_CONFIG[requisition.urgency]
  const daysLeft = getDaysUntilDeadline(requisition.hardDeadline)
  const daysPending = getDaysSinceCreated(requisition.createdAt)
  const isOverdue = daysLeft < 0
  const isAtRisk = daysLeft >= 0 && daysLeft <= 7
  const isPendingTooLong = daysPending > 2

  return (
    <Card className={cn(
      'transition-all hover:shadow-md',
      isPendingTooLong && 'border-amber-200 dark:border-amber-800',
      requisition.urgency === 'critica' && 'border-red-200 dark:border-red-800'
    )}>
      <CardContent className="p-4">
        <div className="flex items-start justify-between gap-4">
          <div className="flex-1 min-w-0">
            {/* Header */}
            <div className="flex items-center gap-2 mb-2">
              <Link 
                href={`/requisiciones/${requisition.id}`}
                className="font-semibold text-primary hover:underline"
              >
                {requisition.id}
              </Link>
              <Badge variant="outline" className={cn('text-xs', urgency.color, urgency.bgColor)}>
                {urgency.label}
              </Badge>
              {isPendingTooLong && (
                <Badge variant="outline" className="text-xs text-amber-600 bg-amber-50 border-amber-200">
                  <Clock className="mr-1 h-3 w-3" />
                  {daysPending}d pendiente
                </Badge>
              )}
            </div>

            {/* Position & Location */}
            <h3 className="font-medium text-base mb-1">{requisition.positionName}</h3>
            <div className="flex items-center gap-4 text-sm text-muted-foreground mb-3">
              <span className="flex items-center gap-1">
                <MapPin className="h-3.5 w-3.5" />
                {requisition.cityName}, {requisition.countryName}
              </span>
              <span className="flex items-center gap-1">
                <Building2 className="h-3.5 w-3.5" />
                {requisition.departmentName}
              </span>
              <span className="flex items-center gap-1">
                <Users className="h-3.5 w-3.5" />
                {requisition.quantity} vacante{requisition.quantity > 1 ? 's' : ''}
              </span>
            </div>

            {/* Justification Preview */}
            <p className="text-sm text-muted-foreground line-clamp-2 mb-3">
              {requisition.justification}
            </p>

            {/* Requester & SLA */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Avatar className="h-6 w-6">
                  <AvatarFallback className="text-xs">
                    {getInitials(requisition.requesterName)}
                  </AvatarFallback>
                </Avatar>
                <span className="text-sm text-muted-foreground">
                  {requisition.requesterName}
                </span>
                <span className="text-xs text-muted-foreground">
                  - {formatDate(requisition.createdAt)}
                </span>
              </div>
              <div className={cn(
                'flex items-center gap-1 text-sm',
                isOverdue && 'text-red-600',
                isAtRisk && !isOverdue && 'text-amber-600'
              )}>
                <Clock className="h-3.5 w-3.5" />
                <span>
                  SLA: {isOverdue ? `${Math.abs(daysLeft)}d vencido` : `${daysLeft}d`}
                </span>
              </div>
            </div>

            {/* HR Approval Info (for Admin view) */}
            {approvalType === 'admin' && requisition.approvedByHrAt && (
              <div className="mt-3 pt-3 border-t">
                <div className="flex items-center gap-2 text-sm text-emerald-600">
                  <CheckCircle2 className="h-4 w-4" />
                  <span>Aprobado por RR.HH. el {formatDate(requisition.approvedByHrAt)}</span>
                </div>
              </div>
            )}

            {/* Compensation (visible to authorized roles) */}
            {(requisition.salaryPackage || requisition.budget) && (
              <div className="mt-3 pt-3 border-t flex items-center gap-4 text-sm">
                <DollarSign className="h-4 w-4 text-muted-foreground" />
                {requisition.salaryPackage && (
                  <span>{requisition.salaryPackage}</span>
                )}
                {requisition.budget && (
                  <span className="text-muted-foreground">
                    Presupuesto: {requisition.currency} {requisition.budget.toLocaleString()}
                  </span>
                )}
              </div>
            )}
          </div>

          {/* Action Buttons */}
          <div className="flex flex-col gap-2">
            <Button size="sm" onClick={() => onApprove(requisition)} className="bg-emerald-600 hover:bg-emerald-700">
              <ThumbsUp className="mr-1 h-4 w-4" />
              Aprobar
            </Button>
            <Button size="sm" variant="outline" onClick={() => onReject(requisition)} className="text-destructive hover:bg-destructive hover:text-destructive-foreground">
              <ThumbsDown className="mr-1 h-4 w-4" />
              Rechazar
            </Button>
            <Button size="sm" variant="ghost" onClick={() => onView(requisition)}>
              <Eye className="mr-1 h-4 w-4" />
              Ver más
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

export function ApprovalsPage() {
  const [searchTerm, setSearchTerm] = React.useState('')
  const [countryFilter, setCountryFilter] = React.useState('all')
  const [activeTab, setActiveTab] = React.useState<'rrhh' | 'admin'>('rrhh')
  
  // Dialog states
  const [selectedRequisition, setSelectedRequisition] = React.useState<Requisition | null>(null)
  const [approveDialogOpen, setApproveDialogOpen] = React.useState(false)
  const [rejectDialogOpen, setRejectDialogOpen] = React.useState(false)
  const [detailDialogOpen, setDetailDialogOpen] = React.useState(false)
  const [rejectComment, setRejectComment] = React.useState('')
  const [approveComment, setApproveComment] = React.useState('')

  // Filter requisitions based on approval type
  const pendingHR = requisitions.filter(r => r.status === 'pendiente_rrhh')
  const pendingAdmin = requisitions.filter(r => r.status === 'pendiente_admin')

  const currentQueue = activeTab === 'rrhh' ? pendingHR : pendingAdmin

  const filteredQueue = React.useMemo(() => {
    let filtered = [...currentQueue]

    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      filtered = filtered.filter(r =>
        r.id.toLowerCase().includes(term) ||
        r.positionName.toLowerCase().includes(term) ||
        r.requesterName.toLowerCase().includes(term)
      )
    }

    if (countryFilter !== 'all') {
      filtered = filtered.filter(r => r.countryId === countryFilter)
    }

    // Sort by urgency and then by date
    filtered.sort((a, b) => {
      const urgencyOrder = { critica: 0, alta: 1, normal: 2 }
      const urgencyDiff = urgencyOrder[a.urgency] - urgencyOrder[b.urgency]
      if (urgencyDiff !== 0) return urgencyDiff
      return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
    })

    return filtered
  }, [currentQueue, searchTerm, countryFilter])

  const handleApprove = (requisition: Requisition) => {
    setSelectedRequisition(requisition)
    setApproveDialogOpen(true)
  }

  const handleReject = (requisition: Requisition) => {
    setSelectedRequisition(requisition)
    setRejectDialogOpen(true)
  }

  const handleView = (requisition: Requisition) => {
    setSelectedRequisition(requisition)
    setDetailDialogOpen(true)
  }

  const confirmApprove = () => {
    if (!selectedRequisition) return
    
    toast.success('Requisición aprobada', {
      description: `${selectedRequisition.id} ha sido aprobada y pasará al siguiente paso.`,
    })
    setApproveDialogOpen(false)
    setApproveComment('')
    setSelectedRequisition(null)
  }

  const confirmReject = () => {
    if (!selectedRequisition || !rejectComment.trim()) return
    
    toast.success('Requisición devuelta', {
      description: `${selectedRequisition.id} ha sido devuelta al solicitante para corrección.`,
    })
    setRejectDialogOpen(false)
    setRejectComment('')
    setSelectedRequisition(null)
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Aprobaciones</h1>
          <p className="text-muted-foreground">
            Gestiona las requisiciones pendientes de aprobación
          </p>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Pendientes RR.HH.</p>
                <p className="text-2xl font-bold">{pendingHR.length}</p>
              </div>
              <div className="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
                <Clock className="h-5 w-5 text-amber-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Pendientes Admin</p>
                <p className="text-2xl font-bold">{pendingAdmin.length}</p>
              </div>
              <div className="h-10 w-10 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
                <Building2 className="h-5 w-5 text-purple-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">Urgentes</p>
                <p className="text-2xl font-bold text-red-600">
                  {[...pendingHR, ...pendingAdmin].filter(r => r.urgency === 'critica').length}
                </p>
              </div>
              <div className="h-10 w-10 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <AlertTriangle className="h-5 w-5 text-red-600" />
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">{'>'}48h Pendientes</p>
                <p className="text-2xl font-bold text-amber-600">
                  {[...pendingHR, ...pendingAdmin].filter(r => getDaysSinceCreated(r.createdAt) > 2).length}
                </p>
              </div>
              <div className="h-10 w-10 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
                <Clock className="h-5 w-5 text-amber-600" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'rrhh' | 'admin')}>
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <TabsList>
            <TabsTrigger value="rrhh" className="gap-2">
              <Users className="h-4 w-4" />
              RR.HH. ({pendingHR.length})
            </TabsTrigger>
            <TabsTrigger value="admin" className="gap-2">
              <Building2 className="h-4 w-4" />
              Administración ({pendingAdmin.length})
            </TabsTrigger>
          </TabsList>

          {/* Filters */}
          <div className="flex items-center gap-2">
            <div className="relative w-64">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Buscar requisición..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={countryFilter} onValueChange={setCountryFilter}>
              <SelectTrigger className="w-[160px]">
                <Filter className="mr-2 h-4 w-4" />
                <SelectValue placeholder="País" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Todos los países</SelectItem>
                {countries.map((country) => (
                  <SelectItem key={country.id} value={country.id}>
                    {country.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <TabsContent value="rrhh" className="mt-6">
          {filteredQueue.length > 0 ? (
            <div className="space-y-4">
              {filteredQueue.map((requisition) => (
                <ApprovalCard
                  key={requisition.id}
                  requisition={requisition}
                  approvalType="rrhh"
                  onApprove={handleApprove}
                  onReject={handleReject}
                  onView={handleView}
                />
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <CheckCircle2 className="h-12 w-12 text-emerald-500 mb-4" />
                <h3 className="text-lg font-semibold">Sin pendientes</h3>
                <p className="text-sm text-muted-foreground">
                  No hay requisiciones pendientes de aprobación de RR.HH.
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="admin" className="mt-6">
          {filteredQueue.length > 0 ? (
            <div className="space-y-4">
              {filteredQueue.map((requisition) => (
                <ApprovalCard
                  key={requisition.id}
                  requisition={requisition}
                  approvalType="admin"
                  onApprove={handleApprove}
                  onReject={handleReject}
                  onView={handleView}
                />
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12 text-center">
                <CheckCircle2 className="h-12 w-12 text-emerald-500 mb-4" />
                <h3 className="text-lg font-semibold">Sin pendientes</h3>
                <p className="text-sm text-muted-foreground">
                  No hay requisiciones pendientes de aprobación de Administración
                </p>
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>

      {/* Approve Dialog */}
      <Dialog open={approveDialogOpen} onOpenChange={setApproveDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Aprobar Requisición</DialogTitle>
            <DialogDescription>
              {selectedRequisition && (
                <>
                  Estás por aprobar <strong>{selectedRequisition.id}</strong> - {selectedRequisition.positionName}
                </>
              )}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="approveComment">Comentario (opcional)</Label>
              <Textarea
                id="approveComment"
                value={approveComment}
                onChange={(e) => setApproveComment(e.target.value)}
                placeholder="Agregar un comentario de aprobación..."
                rows={3}
              />
            </div>
            {activeTab === 'rrhh' && (
              <div className="rounded-lg bg-muted/50 p-3 text-sm">
                <p className="text-muted-foreground">
                  Al aprobar, la requisición pasará a <strong>Pendiente Administración</strong> para aprobación financiera.
                </p>
              </div>
            )}
            {activeTab === 'admin' && (
              <div className="rounded-lg bg-emerald-50 dark:bg-emerald-950/30 p-3 text-sm border border-emerald-200 dark:border-emerald-800">
                <p className="text-emerald-700 dark:text-emerald-300">
                  Al aprobar, la requisición pasará a <strong>Reclutando</strong> y se habilitará para asignar reclutador.
                </p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setApproveDialogOpen(false)}>
              Cancelar
            </Button>
            <Button onClick={confirmApprove} className="bg-emerald-600 hover:bg-emerald-700">
              <CheckCircle2 className="mr-2 h-4 w-4" />
              Confirmar Aprobación
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject Dialog */}
      <Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Rechazar / Solicitar Corrección</DialogTitle>
            <DialogDescription>
              {selectedRequisition && (
                <>
                  La requisición <strong>{selectedRequisition.id}</strong> será devuelta al solicitante para corrección.
                </>
              )}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="rejectComment">Motivo del rechazo / corrección requerida *</Label>
              <Textarea
                id="rejectComment"
                value={rejectComment}
                onChange={(e) => setRejectComment(e.target.value)}
                placeholder="Describe qué información falta o debe corregirse..."
                rows={4}
              />
              <p className="text-xs text-muted-foreground">
                Este comentario será visible para el solicitante.
              </p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setRejectDialogOpen(false)}>
              Cancelar
            </Button>
            <Button 
              variant="destructive" 
              onClick={confirmReject}
              disabled={!rejectComment.trim()}
            >
              <XCircle className="mr-2 h-4 w-4" />
              Confirmar Rechazo
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Detail Dialog */}
      <Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Detalle de Requisición</DialogTitle>
          </DialogHeader>
          {selectedRequisition && (
            <ScrollArea className="max-h-[60vh]">
              <div className="space-y-6 pr-4">
                {/* Header Info */}
                <div className="flex items-start justify-between">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-semibold">{selectedRequisition.id}</span>
                      <Badge variant="outline" className={cn(
                        'text-xs',
                        URGENCY_CONFIG[selectedRequisition.urgency].color,
                        URGENCY_CONFIG[selectedRequisition.urgency].bgColor
                      )}>
                        {URGENCY_CONFIG[selectedRequisition.urgency].label}
                      </Badge>
                    </div>
                    <h3 className="text-lg font-semibold">{selectedRequisition.positionName}</h3>
                  </div>
                </div>

                <Separator />

                {/* Details Grid */}
                <div className="grid gap-4 sm:grid-cols-2">
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Ubicación</p>
                    <p className="font-medium">{selectedRequisition.cityName}, {selectedRequisition.countryName}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Departamento</p>
                    <p className="font-medium">{selectedRequisition.departmentName}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Cantidad de Vacantes</p>
                    <p className="font-medium">{selectedRequisition.quantity}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Modalidad</p>
                    <p className="font-medium capitalize">{selectedRequisition.modalidad}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Tipo de Contratación</p>
                    <p className="font-medium capitalize">{selectedRequisition.tipoContratacion}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">Fecha Límite SLA</p>
                    <p className="font-medium">{formatDate(selectedRequisition.hardDeadline)}</p>
                  </div>
                </div>

                <Separator />

                {/* Justification */}
                <div>
                  <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                    Justificación
                  </h4>
                  <p className="text-sm">{selectedRequisition.justification}</p>
                </div>

                {/* Compensation */}
                {(selectedRequisition.salaryPackage || selectedRequisition.budget) && (
                  <>
                    <Separator />
                    <div>
                      <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                        Compensación
                      </h4>
                      <div className="grid gap-4 sm:grid-cols-2">
                        {selectedRequisition.salaryPackage && (
                          <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">Paquete Salarial</p>
                            <p className="font-medium">{selectedRequisition.salaryPackage}</p>
                          </div>
                        )}
                        {selectedRequisition.budget && (
                          <div className="space-y-1">
                            <p className="text-sm text-muted-foreground">Presupuesto</p>
                            <p className="font-medium">
                              {selectedRequisition.currency} {selectedRequisition.budget.toLocaleString()}
                            </p>
                          </div>
                        )}
                      </div>
                    </div>
                  </>
                )}

                {/* Requester */}
                <Separator />
                <div className="flex items-center gap-3">
                  <Avatar>
                    <AvatarFallback>{getInitials(selectedRequisition.requesterName)}</AvatarFallback>
                  </Avatar>
                  <div>
                    <p className="font-medium">{selectedRequisition.requesterName}</p>
                    <p className="text-sm text-muted-foreground">
                      Solicitante - {formatDate(selectedRequisition.createdAt)}
                    </p>
                  </div>
                </div>
              </div>
            </ScrollArea>
          )}
          <DialogFooter className="flex-row gap-2 sm:justify-between">
            <Button variant="outline" asChild>
              <Link href={`/requisiciones/${selectedRequisition?.id}`}>
                Ver página completa
                <ArrowRight className="ml-2 h-4 w-4" />
              </Link>
            </Button>
            <div className="flex gap-2">
              <Button
                variant="outline"
                className="text-destructive"
                onClick={() => {
                  setDetailDialogOpen(false)
                  if (selectedRequisition) handleReject(selectedRequisition)
                }}
              >
                <ThumbsDown className="mr-2 h-4 w-4" />
                Rechazar
              </Button>
              <Button
                className="bg-emerald-600 hover:bg-emerald-700"
                onClick={() => {
                  setDetailDialogOpen(false)
                  if (selectedRequisition) handleApprove(selectedRequisition)
                }}
              >
                <ThumbsUp className="mr-2 h-4 w-4" />
                Aprobar
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
