"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import {
  ArrowLeft,
  User,
  Star,
  Mail,
  Phone,
  ChevronRight,
  Plus,
  X,
  MoreVertical,
} from "lucide-react";

interface PipelineStage {
  id: number;
  name: string;
  order: number;
  type: string;
  candidates: any[];
}

interface Candidate {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  rating: number;
  source: string;
  summary: string;
  pipelineId: number;
  notes: string;
}

interface JobPipeline {
  id: number;
  title: string;
  stages: PipelineStage[];
}

export default function JobPipelinePage() {
  const params = useParams();
  const router = useRouter();
  const jobId = params.id as string;
  const [pipeline, setPipeline] = useState<JobPipeline | null>(null);
  const [loading, setLoading] = useState(true);
  const [draggedCandidate, setDraggedCandidate] = useState<{
    candidate: Candidate;
    fromStageId: number;
  } | null>(null);
  const [showAddModal, setShowAddModal] = useState(false);
  const [newCandidate, setNewCandidate] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    source: "direct",
    summary: "",
  });

  useEffect(() => {
    fetch(`/api/jobs/${jobId}`)
      .then((res) => res.json())
      .then((data) => {
        setPipeline(data);
        setLoading(false);
      });
  }, [jobId]);

  const handleDragStart = (candidate: Candidate, stageId: number) => {
    setDraggedCandidate({ candidate, fromStageId: stageId });
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = async (toStageId: number) => {
    if (!draggedCandidate) return;

    try {
      await fetch("/api/pipeline/move", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          candidateId: draggedCandidate.candidate.id,
          fromStageId: draggedCandidate.fromStageId,
          toStageId,
          jobId: parseInt(jobId),
        }),
      });

      // Refresh pipeline
      const res = await fetch(`/api/jobs/${jobId}`);
      const data = await res.json();
      setPipeline(data);
    } catch (error) {
      console.error("Failed to move candidate:", error);
    }

    setDraggedCandidate(null);
  };

  const handleAddCandidate = async () => {
    if (!pipeline) return;

    const appliedStage = pipeline.stages.find((s) => s.type === "applied");
    const res = await fetch("/api/candidates", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ...newCandidate,
        jobId: parseInt(jobId),
        stageId: appliedStage?.id,
      }),
    });

    if (res.ok) {
      setShowAddModal(false);
      setNewCandidate({
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
        source: "direct",
        summary: "",
      });

      const data = await fetch(`/api/jobs/${jobId}`).then((r) => r.json());
      setPipeline(data);
    }
  };

  const stageColors: Record<string, string> = {
    applied: "border-t-gray-400",
    screening: "border-t-blue-500",
    interview: "border-t-purple-500",
    assessment: "border-t-amber-500",
    offer: "border-t-green-500",
    hired: "border-t-emerald-500",
    rejected: "border-t-red-500",
  };

  const stageBgColors: Record<string, string> = {
    applied: "bg-gray-50",
    screening: "bg-blue-50/50",
    interview: "bg-purple-50/50",
    assessment: "bg-amber-50/50",
    offer: "bg-green-50/50",
    hired: "bg-emerald-50/50",
    rejected: "bg-red-50/50",
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (!pipeline) {
    return <div className="p-6 text-center text-gray-500">Pipeline not found</div>;
  }

  return (
    <div className="flex flex-col h-screen">
      {/* Header */}
      <div className="flex items-center gap-3 px-6 py-4 bg-white border-b border-gray-200">
        <Link
          href={`/jobs/${jobId}`}
          className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <ArrowLeft className="w-5 h-5 text-gray-500" />
        </Link>
        <div>
          <h1 className="text-lg font-semibold text-gray-900">{pipeline.title}</h1>
          <p className="text-sm text-gray-500">Pipeline View</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="ml-auto flex items-center gap-2 bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
        >
          <Plus className="w-4 h-4" />
          Add Candidate
        </button>
      </div>

      {/* Kanban Board */}
      <div className="flex-1 overflow-x-auto overflow-y-hidden p-4">
        <div className="flex gap-4 min-w-max">
          {pipeline.stages.map((stage) => (
            <div
              key={stage.id}
              className={`w-72 ${stageBgColors[stage.type] || "bg-gray-50"} rounded-xl border-t-4 ${
                stageColors[stage.type] || "border-t-gray-300"
              } flex flex-col max-h-full`}
              onDragOver={handleDragOver}
              onDrop={() => handleDrop(stage.id)}
            >
              {/* Stage Header */}
              <div className="p-3 flex items-center justify-between">
                <h3 className="font-semibold text-gray-900 text-sm">{stage.name}</h3>
                <span className="bg-white text-gray-600 text-xs font-medium px-2 py-0.5 rounded-full border border-gray-200">
                  {stage.candidates.length}
                </span>
              </div>

              {/* Candidates */}
              <div className="flex-1 overflow-y-auto p-2 space-y-2">
                {stage.candidates.map((candidate) => (
                  <Link
                    key={candidate.id}
                    href={`/candidates/${candidate.id}`}
                    draggable
                    onDragStart={() => handleDragStart(candidate, stage.id)}
                    className="kanban-card block bg-white rounded-lg border border-gray-200 p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md"
                  >
                    <div className="flex items-center gap-2.5 mb-2">
                      <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center text-sm font-medium text-blue-700">
                        {candidate.firstName[0]}
                        {candidate.lastName[0]}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate">
                          {candidate.firstName} {candidate.lastName}
                        </p>
                        <p className="text-xs text-gray-500 truncate">{candidate.email}</p>
                      </div>
                    </div>
                    {candidate.summary && (
                      <p className="text-xs text-gray-500 line-clamp-2 mb-2">
                        {candidate.summary}
                      </p>
                    )}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <Star
                            key={star}
                            className={`w-3 h-3 ${
                              star <= (candidate.rating || 0)
                                ? "fill-amber-400 text-amber-400"
                                : "text-gray-300"
                            }`}
                          />
                        ))}
                      </div>
                      <span className="text-xs text-gray-400 capitalize">{candidate.source}</span>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Add Candidate Modal */}
      {showAddModal && (
        <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">Add Candidate</h2>
              <button
                onClick={() => setShowAddModal(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 className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">First Name</label>
                  <input
                    type="text"
                    value={newCandidate.firstName}
                    onChange={(e) => setNewCandidate({ ...newCandidate, firstName: e.target.value })}
                    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">Last Name</label>
                  <input
                    type="text"
                    value={newCandidate.lastName}
                    onChange={(e) => setNewCandidate({ ...newCandidate, lastName: e.target.value })}
                    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>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input
                  type="email"
                  value={newCandidate.email}
                  onChange={(e) => setNewCandidate({ ...newCandidate, email: e.target.value })}
                  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">Phone</label>
                <input
                  type="text"
                  value={newCandidate.phone}
                  onChange={(e) => setNewCandidate({ ...newCandidate, phone: e.target.value })}
                  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">Source</label>
                <select
                  value={newCandidate.source}
                  onChange={(e) => setNewCandidate({ ...newCandidate, source: e.target.value })}
                  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="direct">Direct</option>
                  <option value="linkedin">LinkedIn</option>
                  <option value="indeed">Indeed</option>
                  <option value="referral">Referral</option>
                  <option value="company_website">Company Website</option>
                  <option value="glassdoor">Glassdoor</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Summary</label>
                <textarea
                  value={newCandidate.summary}
                  onChange={(e) => setNewCandidate({ ...newCandidate, summary: e.target.value })}
                  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"
                />
              </div>
            </div>
            <div className="flex items-center justify-end gap-3 p-5 border-t border-gray-200">
              <button
                onClick={() => setShowAddModal(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={handleAddCandidate}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
              >
                Add Candidate
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
