"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Calendar,
  Clock,
  Video,
  Phone,
  MapPin,
  Users,
  Plus,
  X,
  ExternalLink,
  Eye,
  CheckCircle2,
} from "lucide-react";

interface Interview {
  id: number;
  title: string;
  type: string;
  scheduledAt: string;
  duration: number;
  location: string;
  meetingLink: string;
  notes: string;
  status: string;
  feedback: string;
  candidate: { id: number; firstName: string; lastName: string; email: string } | null;
  job: { id: number; title: string } | null;
  interviewer: { id: number; name: string } | null;
}

export default function InterviewsPage() {
  const [interviews, setInterviews] = useState<Interview[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState("upcoming");
  const [showScheduleModal, setShowScheduleModal] = useState(false);

  useEffect(() => {
    fetch(`/api/interviews?upcoming=${filter === "upcoming"}`)
      .then((res) => res.json())
      .then((data) => {
        setInterviews(data);
        setLoading(false);
      });
  }, [filter]);

  const typeIcons: Record<string, any> = {
    phone: Phone,
    video: Video,
    onsite: MapPin,
    technical: Users,
  };

  const typeColors: Record<string, string> = {
    phone: "bg-green-100 text-green-600",
    video: "bg-blue-100 text-blue-600",
    onsite: "bg-purple-100 text-purple-600",
    technical: "bg-amber-100 text-amber-600",
  };

  const statusColors: Record<string, string> = {
    scheduled: "bg-blue-100 text-blue-700",
    completed: "bg-green-100 text-green-700",
    cancelled: "bg-red-100 text-red-700",
    no_show: "bg-gray-100 text-gray-700",
  };

  const groupByDate = (interviews: Interview[]) => {
    const groups: Record<string, Interview[]> = {};
    interviews.forEach((interview) => {
      const date = new Date(interview.scheduledAt).toLocaleDateString("en-US", {
        weekday: "long",
        month: "long",
        day: "numeric",
        year: "numeric",
      });
      if (!groups[date]) groups[date] = [];
      groups[date].push(interview);
    });
    return groups;
  };

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Interviews</h1>
          <p className="text-gray-500 mt-1">Manage and schedule interviews with candidates</p>
        </div>
        <button
          onClick={() => setShowScheduleModal(true)}
          className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2.5 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
        >
          <Plus className="w-5 h-5" />
          Schedule Interview
        </button>
      </div>

      {/* Filter Tabs */}
      <div className="flex items-center gap-2 mb-6">
        <button
          onClick={() => setFilter("upcoming")}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
            filter === "upcoming"
              ? "bg-blue-600 text-white"
              : "bg-white text-gray-600 hover:bg-gray-100 border border-gray-200"
          }`}
        >
          Upcoming
        </button>
        <button
          onClick={() => setFilter("all")}
          className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
            filter === "all"
              ? "bg-blue-600 text-white"
              : "bg-white text-gray-600 hover:bg-gray-100 border border-gray-200"
          }`}
        >
          All Interviews
        </button>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
        </div>
      ) : (
        <div className="space-y-6">
          {Object.entries(groupByDate(interviews)).map(([date, dateInterviews]) => (
            <div key={date}>
              <h3 className="text-sm font-semibold text-gray-500 mb-3">{date}</h3>
              <div className="space-y-3">
                {dateInterviews.map((interview) => {
                  const TypeIcon = typeIcons[interview.type] || Calendar;
                  return (
                    <div
                      key={interview.id}
                      className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 hover:shadow-md transition-shadow"
                    >
                      <div className="flex items-start gap-4">
                        <div
                          className={`p-3 rounded-lg ${
                            typeColors[interview.type] || "bg-gray-100 text-gray-600"
                          }`}
                        >
                          <TypeIcon className="w-5 h-5" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-start justify-between">
                            <div>
                              <h4 className="font-semibold text-gray-900">{interview.title}</h4>
                              {interview.candidate && (
                                <Link
                                  href={`/candidates/${interview.candidate.id}`}
                                  className="text-sm text-blue-600 hover:text-blue-700 mt-0.5"
                                >
                                  {interview.candidate.firstName} {interview.candidate.lastName}
                                </Link>
                              )}
                              {interview.job && (
                                <p className="text-sm text-gray-500 mt-0.5">{interview.job.title}</p>
                              )}
                            </div>
                            <span
                              className={`text-xs px-2.5 py-1 rounded-full font-medium capitalize ${
                                statusColors[interview.status] || "bg-gray-100 text-gray-700"
                              }`}
                            >
                              {interview.status.replace("_", " ")}
                            </span>
                          </div>
                          <div className="flex items-center gap-4 mt-3 text-sm text-gray-500">
                            <span className="flex items-center gap-1.5">
                              <Clock className="w-4 h-4" />
                              {new Date(interview.scheduledAt).toLocaleTimeString("en-US", {
                                hour: "2-digit",
                                minute: "2-digit",
                              })}{" "}
                              ({interview.duration} min)
                            </span>
                            {interview.interviewer && (
                              <span className="flex items-center gap-1.5">
                                <Users className="w-4 h-4" />
                                {interview.interviewer.name}
                              </span>
                            )}
                            {interview.meetingLink && (
                              <a
                                href={interview.meetingLink}
                                target="_blank"
                                className="flex items-center gap-1 text-blue-600 hover:text-blue-700"
                              >
                                <ExternalLink className="w-4 h-4" />
                                Join
                              </a>
                            )}
                          </div>
                          {interview.notes && (
                            <p className="text-sm text-gray-500 mt-2 bg-gray-50 p-2 rounded">
                              {interview.notes}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
          {interviews.length === 0 && (
            <div className="text-center py-16 bg-white rounded-xl border border-gray-200">
              <Calendar className="w-12 h-12 text-gray-300 mx-auto mb-3" />
              <h3 className="text-lg font-medium text-gray-900 mb-1">
                {filter === "upcoming" ? "No upcoming interviews" : "No interviews found"}
              </h3>
              <p className="text-sm text-gray-500">
                {filter === "upcoming"
                  ? "Schedule your first interview to get started"
                  : "No interviews match your filters"}
              </p>
            </div>
          )}
        </div>
      )}

      {/* Schedule Modal */}
      {showScheduleModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md">
            <div className="flex items-center justify-between p-5 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Schedule Interview</h2>
              <button
                onClick={() => setShowScheduleModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Candidate</label>
                <input
                  type="text"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  placeholder="Search candidate..."
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
                  <select className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                    <option value="video">Video</option>
                    <option value="phone">Phone</option>
                    <option value="onsite">On-site</option>
                    <option value="technical">Technical</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Duration</label>
                  <select className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                    <option value={15}>15 min</option>
                    <option value={30}>30 min</option>
                    <option value={45}>45 min</option>
                    <option value={60}>60 min</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Date & Time</label>
                <input
                  type="datetime-local"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Meeting Link</label>
                <input
                  type="text"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                  placeholder="Zoom/Google Meet link"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Notes</label>
                <textarea
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm h-20 resize-none"
                  placeholder="Interview notes..."
                />
              </div>
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowScheduleModal(false)}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => setShowScheduleModal(false)}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
              >
                Schedule
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
