"use client";

import React, { useRef, useState } from "react";
import { X, UploadCloud, Loader2 } from "lucide-react";
import { api } from "@/services/api";
import { toast } from "sonner";

interface AddResumeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export function AddResumeModal({ isOpen, onClose, onSuccess }: AddResumeModalProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);

  if (!isOpen) return null;

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const validTypes = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"];
      if (!validTypes.includes(file.type)) {
        toast.error("Please select a PDF, DOC, or DOCX file.");
        return;
      }
      if (file.size > 5 * 1024 * 1024) {
        toast.error("File must be smaller than 5MB.");
        return;
      }
      setSelectedFile(file);
    }
  };

  const handleSave = async () => {
    if (!selectedFile) {
      toast.error("Please upload a resume first.");
      return;
    }

    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append("resume", selectedFile);
      formData.append("resume_name", selectedFile.name);

      await api.post("/seeker_resumes/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });

      toast.success("Resume uploaded successfully!");
      onSuccess();
    } catch (error: any) {
      toast.error(error?.response?.data?.message || "Failed to upload resume.");
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <div className="bg-white rounded-[20px] w-full max-w-md p-6 relative">
        <button 
          onClick={onClose}
          className="absolute top-4 right-4 text-gray-500 hover:text-black transition-colors"
        >
          <X className="w-6 h-6" strokeWidth={1.5} />
        </button>

        <h2 className="text-[22px] font-bold text-center mb-6">Add CV/Resume</h2>

        <div className="mb-4">
          <label className="text-[15px] text-black block mb-3">
            Upload CV/Resume<span className="text-red-500 font-bold ml-1">*</span>
          </label>
          
          <div 
            className="border border-gray-200 rounded-xl p-8 flex flex-col items-center justify-center text-center hover:bg-gray-50 transition-colors cursor-pointer"
            onClick={() => fileInputRef.current?.click()}
          >
            <UploadCloud className="w-8 h-8 text-black mb-3" strokeWidth={1.5} />
            <p className="text-[13px] text-gray-500 mb-1">
              Upload your resume PDF, DOC, DOCX
            </p>
            <p className="text-[13px] text-gray-500 mb-4">
              (Max 5MB)
            </p>
            
            <button className="px-5 py-1.5 bg-white border border-[#ff6b00] text-[#ff6b00] rounded text-sm font-medium hover:bg-orange-50 transition-colors shadow-sm">
              Upload resume
            </button>
            <input 
              type="file" 
              ref={fileInputRef} 
              className="hidden" 
              accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
              onChange={handleFileChange}
            />
          </div>
          {selectedFile && (
            <p className="text-sm text-green-600 mt-2 font-medium text-center">
              Selected: {selectedFile.name}
            </p>
          )}
        </div>

        <div className="flex items-center justify-center gap-6 mt-8">
          <button 
            onClick={onClose}
            className="font-bold text-[15px] text-black hover:text-gray-700 transition-colors"
          >
            Cancel
          </button>
          <button 
            onClick={handleSave}
            disabled={isUploading || !selectedFile}
            className="px-12 py-2.5 bg-[#ff6b00] hover:bg-[#e66000] text-white font-bold rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
          >
            {isUploading ? <Loader2 className="w-5 h-5 animate-spin" /> : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}
