"use client";

import React, { useState, useEffect, useRef } from "react";
import Image from "next/image";
import { format } from "date-fns";
import {
  MoreVertical,
  Eye,
  Download,
  RefreshCw,
  Trash2,
  FileText,
} from "lucide-react";
import { profileService } from "@/services/profile.service";
import { toast } from "sonner";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import dynamic from "next/dynamic";
const PreviewResumeModal = dynamic(() => import("./PreviewResumeModal"), {
  ssr: false,
});

interface Resume {
  id: number;
  seeker_id: number;
  file_url: string;
  file_name: string;
  name: string;
  uploaded_at: string;
  is_deleted: boolean;
}

export function ResumeCard() {
  const [resumes, setResumes] = useState<Resume[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [previewResume, setPreviewResume] = useState<Resume | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const replaceInputRef = useRef<HTMLInputElement>(null);
  const [replaceId, setReplaceId] = useState<number | null>(null);

  const fetchResumes = async () => {
    try {
      setLoading(true);
      const res = await profileService.getSeekerResumes();
      setResumes(res.resumes || []);
    } catch (err) {
      toast.error("Failed to fetch resumes");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchResumes();
  }, []);

  const handleUploadClick = () => {
    if (resumes.length >= 5) {
      toast.error("You can only upload a maximum of 5 resumes.");
      return;
    }
    fileInputRef.current?.click();
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.size > 5 * 1024 * 1024) {
      toast.error("File size exceeds 5MB limit.");
      return;
    }

    try {
      setUploading(true);
      await profileService.uploadSeekerResume(file);
      toast.success("Resume uploaded successfully");
      fetchResumes();
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "Failed to upload resume");
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await profileService.deleteSeekerResume(id);
      toast.success("Resume deleted successfully");
      fetchResumes();
    } catch (err) {
      toast.error("Failed to delete resume");
    }
  };

  const handleReplaceClick = (id: number) => {
    setReplaceId(id);
    replaceInputRef.current?.click();
  };

  const handleReplaceFileChange = async (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = e.target.files?.[0];
    if (!file || !replaceId) return;

    if (file.size > 5 * 1024 * 1024) {
      toast.error("File size exceeds 5MB limit.");
      return;
    }

    try {
      setUploading(true);
      await profileService.replaceSeekerResume(replaceId, file);
      toast.success("Resume replaced successfully");
      fetchResumes();
    } catch (err: any) {
      toast.error(err?.response?.data?.message || "Failed to replace resume");
    } finally {
      setUploading(false);
      setReplaceId(null);
      if (replaceInputRef.current) replaceInputRef.current.value = "";
    }
  };

  const getBackendUrl = (path: string) => {
    const cleanPath = path.replace(/\\/g, "/"); // Normalize windows slashes
    // Use the Next.js proxy to avoid CORS errors with fetch/react-pdf
    return `/api/proxy/${cleanPath}`;
  };

  return (
    <div className="bg-white rounded-3xl p-8 border border-gray-100 shadow-sm">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-xl font-bold text-gray-800">Resume</h2>
      </div>

      <div className="flex flex-col gap-3">
        {loading ? (
          <p className="text-sm text-gray-500">Loading resumes...</p>
        ) : resumes.length === 0 ? (
          <p className="text-sm text-gray-500">No resumes uploaded yet.</p>
        ) : (
          resumes.map((resume) => (
            <div
              key={resume.id}
              className="flex items-center justify-between p-4 border border-gray-200 rounded-xl"
            >
              <div className="flex items-center space-x-4">
                <div className="p-3 bg-orange-50 rounded-lg relative">
                  <Image 
                    src="/images/resume.png" 
                    alt="Resume Icon" 
                    width={32} 
                    height={32} 
                    className="object-contain"
                  />
                </div>
                <div>
                  <h4 className="text-[15px] font-semibold text-gray-800">
                    {resume.name}
                  </h4>
                  <p className="text-[13px] text-gray-500">
                    Uploaded {format(new Date(resume.uploaded_at), "d MMM yyyy")}
                  </p>
                </div>
              </div>

              <DropdownMenu>
                <DropdownMenuTrigger className="p-2 hover:bg-gray-100 rounded-full transition-colors outline-none focus:outline-none">
                  <MoreVertical className="w-5 h-5 text-gray-500" />
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-40 bg-white rounded-xl shadow-lg border border-gray-100 py-2">
                  <DropdownMenuItem
                    onClick={() => setPreviewResume(resume)}
                    className="cursor-pointer px-4 py-2 hover:bg-gray-50 outline-none"
                  >
                    <Eye className="w-4 h-4 mr-3 text-gray-600" />
                    <span className="text-[14px] text-gray-700">Preview</span>
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    className="cursor-pointer p-0 hover:bg-gray-50 outline-none"
                  >
                    <a
                      href={getBackendUrl(resume.file_url)}
                      download={resume.name}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center w-full px-4 py-2"
                    >
                      <Download className="w-4 h-4 mr-3 text-gray-600" />
                      <span className="text-[14px] text-gray-700">Download</span>
                    </a>
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleReplaceClick(resume.id)}
                    className="cursor-pointer px-4 py-2 hover:bg-gray-50 outline-none"
                  >
                    <RefreshCw className="w-4 h-4 mr-3 text-gray-600" />
                    <span className="text-[14px] text-gray-700">Replace</span>
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => handleDelete(resume.id)}
                    className="cursor-pointer px-4 py-2 hover:bg-red-50 outline-none"
                  >
                    <Trash2 className="w-4 h-4 mr-3 text-red-500" />
                    <span className="text-[14px] text-red-600">Delete</span>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          ))
        )}

        <button
          onClick={handleUploadClick}
          disabled={uploading || resumes.length >= 5}
          className="w-full py-3 border border-[#ff6b00] text-[#ff6b00] font-semibold rounded-xl hover:bg-orange-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center text-[15px]"
        >
          {uploading
            ? "Uploading..."
            : resumes.length === 0
            ? "Upload resume"
            : "Add another resume"}
        </button>
        <p className="text-center text-[13px] text-gray-400">
          Upload pdf, doc, or docx files only Max file size 5MB
        </p>
      </div>

      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        accept=".pdf,.doc,.docx"
        className="hidden"
      />
      <input
        type="file"
        ref={replaceInputRef}
        onChange={handleReplaceFileChange}
        accept=".pdf,.doc,.docx"
        className="hidden"
      />

      {previewResume && (
        <PreviewResumeModal
          isOpen={!!previewResume}
          onClose={() => setPreviewResume(null)}
          resumeName={previewResume.name}
          resumeUrl={getBackendUrl(previewResume.file_url)}
        />
      )}
    </div>
  );
}
