import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Search, ChevronDown, X } from "lucide-react";
import { useUpdateBasicDetails } from "@/hooks/useProfile";
import { api } from "@/services/api";

interface EditKeySkillsModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
}

export function EditKeySkillsModal({ isOpen, onClose, user }: EditKeySkillsModalProps) {
  const profile = user?.seekerProfile || {};
  const userSkills = user?.skills || [];
  
  const updateMutation = useUpdateBasicDetails();
  
  const [skills, setSkills] = useState<any[]>(userSkills);
  const [allSkills, setAllSkills] = useState<any[]>([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);

  const addSkill = (skill: any) => {
    if (!skills.some(s => (s.id === skill.id) || (s.skill_name === skill.skill_name || s === skill.skill_name))) {
      setSkills([...skills, skill]);
      setSearchQuery("");
      setIsDropdownOpen(false);
    }
  };

  useEffect(() => {
    if (isOpen) {
      setSkills(user?.skills || []);
      setSearchQuery("");
      setIsDropdownOpen(false);
      api.get('/skills').then(res => setAllSkills(res.data)).catch(console.error);
    }
  }, [isOpen, user]);

  const filteredSkills = allSkills.filter(s => 
    s.skill_name.toLowerCase().includes(searchQuery.toLowerCase()) && 
    !skills.some(selected => selected.id === s.id)
  );

  const removeSkill = (indexToRemove: number) => {
    setSkills(skills.filter((_, index) => index !== indexToRemove));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Send array of IDs (mocking by taking id from the object, if it doesn't exist, this implies a new skill we can't save right now without a master table API, but we'll try)
    const skills_ids = skills.map(s => s.id).filter(id => id !== undefined);
    
    updateMutation.mutate({
      skills_ids
    }, {
      onSuccess: () => {
        onClose();
      }
    });
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-[700px] w-full max-h-[80vh] p-0 overflow-hidden bg-[#fafafa] rounded-2xl border-0 shadow-2xl flex flex-col">
        
        {/* Header */}
        <div className="p-8 pb-4">
          <DialogTitle className="text-2xl font-bold text-gray-900 mb-2">Key Skills</DialogTitle>
          <p className="text-sm font-medium text-gray-500">Add skills that best define your expertise</p>
        </div>

        {/* Scrollable Body */}
        <div className="px-8 pb-6 flex-1 overflow-y-auto">
          <div className="flex flex-col gap-6">
            
            {/* Search Input */}
            <div className="relative">
              <button 
                type="button"
                onClick={() => setIsDropdownOpen(true)}
                className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 focus:outline-none"
              >
                <Search className="w-5 h-5" />
              </button>
              <input 
                type="text"
                placeholder="Search skills..."
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value);
                  setIsDropdownOpen(true);
                }}
                onClick={() => setIsDropdownOpen(true)}
                className="w-full h-11 pl-12 pr-12 rounded-xl !border-0 shadow-[0_4px_8px_-2px_rgba(0,0,0,0.25)] ring-1 ring-inset ring-gray-100 bg-white text-sm font-medium text-gray-700 placeholder:font-normal focus:outline-none"
              />
              <div className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none">
                <ChevronDown className="w-5 h-5" />
              </div>

              {/* Dropdown */}
              {isDropdownOpen && filteredSkills.length > 0 && (
                <div className="absolute z-10 w-full mt-2 bg-white rounded-xl shadow-lg border border-gray-100 max-h-60 overflow-y-auto">
                  {filteredSkills.map(skill => (
                    <div
                      key={skill.id}
                      onClick={() => addSkill(skill)}
                      className="px-4 py-3 hover:bg-gray-50 cursor-pointer text-sm font-medium text-gray-700 transition-colors border-b border-gray-50 last:border-0"
                    >
                      {skill.skill_name}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Selected Skills Tags */}
            <div className="flex flex-wrap gap-x-3 gap-y-3 pt-2">
              {skills.map((skill, index) => (
                <div 
                  key={index} 
                  className="flex items-center gap-2 px-4 py-1.5 rounded-full border border-[#ff6b00] bg-white shadow-[0_2px_8px_rgba(255,107,0,0.15)] text-[#ff6b00] text-sm font-medium"
                >
                  <span>{skill.skill_name || skill}</span>
                  <button 
                    onClick={() => removeSkill(index)}
                    className="hover:bg-[#fff0e6] rounded-full p-0.5 transition-colors flex items-center justify-center"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </div>
              ))}
            </div>
            
            {/* Some extra padding to match screenshot whitespace */}
            <div className="h-20"></div>

          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-4 p-6 pt-4 bg-[#fafafa]">
          <button type="button" onClick={onClose} className="text-sm font-bold text-gray-900 hover:text-gray-700 px-2 py-2">
            Cancel
          </button>
          <Button onClick={handleSubmit} className="bg-[#ff6b00] hover:bg-[#e65c00] text-white px-8 h-10 rounded-lg font-bold border-0 shadow-sm min-w-[120px]">
            Save
          </Button>
        </div>

      </DialogContent>
    </Dialog>
  );
}
