"use client"

import { useState } from "react"
import { mockInterviews, mockCandidates, mockRequisitions, mockUsers } from "@/lib/mock-data"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Calendar } from "@/components/ui/calendar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  ChevronLeft, 
  ChevronRight, 
  Plus, 
  Video, 
  MapPin, 
  Clock, 
  User,
  Calendar as CalendarIcon,
  Users,
  MoreVertical,
  Mail,
  Phone,
  FileText,
  CheckCircle2,
  XCircle,
  Edit,
  Trash2,
  ExternalLink
} from "lucide-react"
import { cn } from "@/lib/utils"

const weekDays = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"]
const monthNames = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]

export function CalendarPage() {
  const [currentDate, setCurrentDate] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState<Date | null>(null)
  const [viewMode, setViewMode] = useState<"month" | "week" | "day">("month")
  const [isNewInterviewOpen, setIsNewInterviewOpen] = useState(false)
  const [selectedInterview, setSelectedInterview] = useState<typeof mockInterviews[0] | null>(null)
  const [filterType, setFilterType] = useState<string>("all")

  const interviews = mockInterviews

  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    const daysInMonth = lastDay.getDate()
    const startingDay = firstDay.getDay()

    const days: (Date | null)[] = []
    
    for (let i = 0; i < startingDay; i++) {
      days.push(null)
    }
    
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(new Date(year, month, i))
    }

    return days
  }

  const getInterviewsForDate = (date: Date) => {
    return interviews.filter(interview => {
      const interviewDate = new Date(interview.scheduledDate)
      return (
        interviewDate.getDate() === date.getDate() &&
        interviewDate.getMonth() === date.getMonth() &&
        interviewDate.getFullYear() === date.getFullYear()
      )
    }).filter(interview => {
      if (filterType === "all") return true
      return interview.type === filterType
    })
  }

  const navigateMonth = (direction: "prev" | "next") => {
    setCurrentDate(prev => {
      const newDate = new Date(prev)
      if (direction === "prev") {
        newDate.setMonth(newDate.getMonth() - 1)
      } else {
        newDate.setMonth(newDate.getMonth() + 1)
      }
      return newDate
    })
  }

  const getInterviewTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      rrhh: "bg-primary text-primary-foreground",
      technical: "bg-blue-500 text-white",
      manager: "bg-purple-500 text-white",
      final: "bg-accent text-accent-foreground"
    }
    return colors[type] || "bg-secondary text-secondary-foreground"
  }

  const getInterviewTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      rrhh: "RR.HH.",
      technical: "Técnica",
      manager: "Gerente",
      final: "Final"
    }
    return labels[type] || type
  }

  const getCandidateName = (candidateId: string) => {
    const candidate = mockCandidates.find(c => c.id === candidateId)
    return candidate?.name || "Candidato"
  }

  const getRequisitionTitle = (requisitionId: string) => {
    const requisition = mockRequisitions.find(r => r.id === requisitionId)
    return requisition?.position || "Vacante"
  }

  const formatTime = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" })
  }

  const days = getDaysInMonth(currentDate)

  const upcomingInterviews = interviews
    .filter(i => new Date(i.scheduledDate) >= new Date())
    .sort((a, b) => new Date(a.scheduledDate).getTime() - new Date(b.scheduledDate).getTime())
    .slice(0, 5)

  const todayInterviews = getInterviewsForDate(new Date())

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Calendario de Entrevistas</h1>
          <p className="text-muted-foreground">
            Gestiona y agenda entrevistas con candidatos
          </p>
        </div>
        <Dialog open={isNewInterviewOpen} onOpenChange={setIsNewInterviewOpen}>
          <DialogTrigger asChild>
            <Button className="bg-accent hover:bg-accent/90 text-accent-foreground">
              <Plus className="mr-2 h-4 w-4" />
              Agendar Entrevista
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>Agendar Nueva Entrevista</DialogTitle>
              <DialogDescription>
                Programa una entrevista con un candidato
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="space-y-2">
                <Label>Candidato</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar candidato" />
                  </SelectTrigger>
                  <SelectContent>
                    {mockCandidates.map(candidate => (
                      <SelectItem key={candidate.id} value={candidate.id}>
                        {candidate.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Tipo de Entrevista</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar tipo" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="rrhh">Entrevista RR.HH.</SelectItem>
                    <SelectItem value="technical">Entrevista Técnica</SelectItem>
                    <SelectItem value="manager">Entrevista Gerente</SelectItem>
                    <SelectItem value="final">Entrevista Final</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Fecha</Label>
                  <Input type="date" />
                </div>
                <div className="space-y-2">
                  <Label>Hora</Label>
                  <Input type="time" />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Duracion (minutos)</Label>
                <Select defaultValue="60">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="30">30 minutos</SelectItem>
                    <SelectItem value="45">45 minutos</SelectItem>
                    <SelectItem value="60">60 minutos</SelectItem>
                    <SelectItem value="90">90 minutos</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Modalidad</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar modalidad" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="video">Videoconferencia</SelectItem>
                    <SelectItem value="presencial">Presencial</SelectItem>
                    <SelectItem value="phone">Telefonica</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Entrevistadores</Label>
                <Select>
                  <SelectTrigger>
                    <SelectValue placeholder="Seleccionar entrevistadores" />
                  </SelectTrigger>
                  <SelectContent>
                    {mockUsers.filter(u => u.role === "recruiter" || u.role === "hr_manager").map(user => (
                      <SelectItem key={user.id} value={user.id}>
                        {user.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Notas</Label>
                <Textarea placeholder="Notas adicionales para la entrevista..." />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsNewInterviewOpen(false)}>
                Cancelar
              </Button>
              <Button className="bg-accent hover:bg-accent/90" onClick={() => setIsNewInterviewOpen(false)}>
                Agendar
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Calendar */}
        <div className="lg:col-span-3">
          <Card>
            <CardHeader className="pb-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <Button variant="outline" size="icon" onClick={() => navigateMonth("prev")}>
                    <ChevronLeft className="h-4 w-4" />
                  </Button>
                  <h2 className="text-xl font-semibold">
                    {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
                  </h2>
                  <Button variant="outline" size="icon" onClick={() => navigateMonth("next")}>
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
                <div className="flex items-center gap-2">
                  <Select value={filterType} onValueChange={setFilterType}>
                    <SelectTrigger className="w-[180px]">
                      <SelectValue placeholder="Filtrar por tipo" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Todos los tipos</SelectItem>
                      <SelectItem value="rrhh">Entrevista RR.HH.</SelectItem>
                      <SelectItem value="technical">Entrevista Técnica</SelectItem>
                      <SelectItem value="manager">Entrevista Gerente</SelectItem>
                      <SelectItem value="final">Entrevista Final</SelectItem>
                    </SelectContent>
                  </Select>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => setCurrentDate(new Date())}
                  >
                    Hoy
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              {/* Week Headers */}
              <div className="grid grid-cols-7 gap-px mb-2">
                {weekDays.map(day => (
                  <div key={day} className="text-center text-sm font-medium text-muted-foreground py-2">
                    {day}
                  </div>
                ))}
              </div>
              
              {/* Calendar Grid */}
              <div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
                {days.map((day, index) => {
                  const dayInterviews = day ? getInterviewsForDate(day) : []
                  const isToday = day && 
                    day.getDate() === new Date().getDate() &&
                    day.getMonth() === new Date().getMonth() &&
                    day.getFullYear() === new Date().getFullYear()
                  const isSelected = day && selectedDate &&
                    day.getDate() === selectedDate.getDate() &&
                    day.getMonth() === selectedDate.getMonth() &&
                    day.getFullYear() === selectedDate.getFullYear()

                  return (
                    <div
                      key={index}
                      className={cn(
                        "min-h-[120px] bg-card p-2 cursor-pointer transition-colors hover:bg-muted/50",
                        !day && "bg-muted/30",
                        isSelected && "ring-2 ring-primary ring-inset"
                      )}
                      onClick={() => day && setSelectedDate(day)}
                    >
                      {day && (
                        <>
                          <div className={cn(
                            "text-sm font-medium mb-1",
                            isToday && "w-7 h-7 rounded-full bg-primary text-primary-foreground flex items-center justify-center"
                          )}>
                            {day.getDate()}
                          </div>
                          <div className="space-y-1">
                            {dayInterviews.slice(0, 3).map(interview => (
                              <div
                                key={interview.id}
                                className={cn(
                                  "text-xs p-1 rounded truncate cursor-pointer",
                                  getInterviewTypeColor(interview.type)
                                )}
                                onClick={(e) => {
                                  e.stopPropagation()
                                  setSelectedInterview(interview)
                                }}
                              >
                                {formatTime(interview.scheduledDate)} - {getCandidateName(interview.candidateId)}
                              </div>
                            ))}
                            {dayInterviews.length > 3 && (
                              <div className="text-xs text-muted-foreground text-center">
                                +{dayInterviews.length - 3} mas
                              </div>
                            )}
                          </div>
                        </>
                      )}
                    </div>
                  )
                })}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Today's Interviews */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">Entrevistas de Hoy</CardTitle>
              <CardDescription>{todayInterviews.length} programadas</CardDescription>
            </CardHeader>
            <CardContent className="space-y-3">
              {todayInterviews.length > 0 ? todayInterviews.map(interview => (
                <div 
                  key={interview.id} 
                  className="p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => setSelectedInterview(interview)}
                >
                  <div className="flex items-center justify-between mb-2">
                    <Badge className={getInterviewTypeColor(interview.type)}>
                      {getInterviewTypeLabel(interview.type)}
                    </Badge>
                    <span className="text-sm font-medium">{formatTime(interview.scheduledDate)}</span>
                  </div>
                  <div className="text-sm font-medium">{getCandidateName(interview.candidateId)}</div>
                  <div className="text-xs text-muted-foreground">{getRequisitionTitle(interview.requisitionId)}</div>
                </div>
              )) : (
                <div className="text-center py-4 text-muted-foreground text-sm">
                  No hay entrevistas hoy
                </div>
              )}
            </CardContent>
          </Card>

          {/* Upcoming */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">Proximas Entrevistas</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {upcomingInterviews.map(interview => (
                <div 
                  key={interview.id} 
                  className="p-3 border rounded-lg cursor-pointer hover:bg-muted/50 transition-colors"
                  onClick={() => setSelectedInterview(interview)}
                >
                  <div className="flex items-center justify-between mb-1">
                    <Badge variant="outline" className="text-xs">
                      {getInterviewTypeLabel(interview.type)}
                    </Badge>
                    <span className="text-xs text-muted-foreground">
                      {new Date(interview.scheduledDate).toLocaleDateString("es-MX", { 
                        day: "numeric", 
                        month: "short" 
                      })}
                    </span>
                  </div>
                  <div className="text-sm font-medium">{getCandidateName(interview.candidateId)}</div>
                  <div className="flex items-center gap-1 text-xs text-muted-foreground mt-1">
                    <Clock className="h-3 w-3" />
                    {formatTime(interview.scheduledDate)}
                  </div>
                </div>
              ))}
            </CardContent>
          </Card>

          {/* Legend */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">Tipos de Entrevista</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded bg-primary" />
                <span className="text-sm">Entrevista RR.HH.</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded bg-blue-500" />
                <span className="text-sm">Entrevista Técnica</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded bg-purple-500" />
                <span className="text-sm">Entrevista Gerente</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded bg-accent" />
                <span className="text-sm">Entrevista Final</span>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Interview Detail Dialog */}
      <Dialog open={!!selectedInterview} onOpenChange={() => setSelectedInterview(null)}>
        <DialogContent className="max-w-lg">
          {selectedInterview && (
            <>
              <DialogHeader>
                <div className="flex items-center justify-between">
                  <Badge className={getInterviewTypeColor(selectedInterview.type)}>
                    {getInterviewTypeLabel(selectedInterview.type)}
                  </Badge>
                  <Badge variant={
                    selectedInterview.status === "scheduled" ? "secondary" :
                    selectedInterview.status === "completed" ? "default" :
                    "destructive"
                  }>
                    {selectedInterview.status === "scheduled" ? "Programada" :
                     selectedInterview.status === "completed" ? "Completada" :
                     "Cancelada"}
                  </Badge>
                </div>
                <DialogTitle className="mt-2">
                  Entrevista con {getCandidateName(selectedInterview.candidateId)}
                </DialogTitle>
                <DialogDescription>
                  {getRequisitionTitle(selectedInterview.requisitionId)}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-4 py-4">
                <div className="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
                  <CalendarIcon className="h-5 w-5 text-muted-foreground" />
                  <div>
                    <div className="font-medium">
                      {new Date(selectedInterview.scheduledDate).toLocaleDateString("es-MX", {
                        weekday: "long",
                        day: "numeric",
                        month: "long",
                        year: "numeric"
                      })}
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {formatTime(selectedInterview.scheduledDate)} - {selectedInterview.duration} minutos
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-3 p-3 bg-muted/50 rounded-lg">
                  {selectedInterview.location === "video" ? (
                    <Video className="h-5 w-5 text-muted-foreground" />
                  ) : (
                    <MapPin className="h-5 w-5 text-muted-foreground" />
                  )}
                  <div>
                    <div className="font-medium">
                      {selectedInterview.location === "video" ? "Videoconferencia" : "Presencial"}
                    </div>
                    {selectedInterview.meetingLink && (
                      <a 
                        href={selectedInterview.meetingLink} 
                        className="text-sm text-primary hover:underline flex items-center gap-1"
                      >
                        Unirse a la reunion <ExternalLink className="h-3 w-3" />
                      </a>
                    )}
                  </div>
                </div>

                <div className="space-y-2">
                  <Label className="text-sm text-muted-foreground">Entrevistadores</Label>
                  <div className="flex flex-wrap gap-2">
                    {selectedInterview.interviewers.map(interviewerId => {
                      const interviewer = mockUsers.find(u => u.id === interviewerId)
                      return interviewer ? (
                        <div key={interviewerId} className="flex items-center gap-2 px-3 py-1.5 bg-muted rounded-full">
                          <Avatar className="h-6 w-6">
                            <AvatarImage src={interviewer.avatar} />
                            <AvatarFallback className="text-xs">
                              {interviewer.name.split(" ").map(n => n[0]).join("")}
                            </AvatarFallback>
                          </Avatar>
                          <span className="text-sm">{interviewer.name}</span>
                        </div>
                      ) : null
                    })}
                  </div>
                </div>

                {selectedInterview.notes && (
                  <div className="space-y-2">
                    <Label className="text-sm text-muted-foreground">Notas</Label>
                    <p className="text-sm p-3 bg-muted/50 rounded-lg">{selectedInterview.notes}</p>
                  </div>
                )}
              </div>

              <DialogFooter className="gap-2">
                <Button variant="outline" size="sm">
                  <Edit className="mr-2 h-4 w-4" />
                  Editar
                </Button>
                <Button variant="outline" size="sm" className="text-destructive">
                  <Trash2 className="mr-2 h-4 w-4" />
                  Cancelar
                </Button>
                {selectedInterview.status === "scheduled" && (
                  <Button size="sm" className="bg-accent hover:bg-accent/90">
                    <CheckCircle2 className="mr-2 h-4 w-4" />
                    Completar
                  </Button>
                )}
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
