// src/components/Onboarding.tsx
'use client'
import { useState } from 'react';
import { X, ArrowRight, Twitter, InstagramIcon, Facebook, Linkedin } from 'lucide-react';
import { createProfile } from '@/lib/api/core';
import { useTheme } from '@/contexts/themecontext';

interface AddProfileProps {
  onComplete: () => void;
}

interface SocialInput {
  type: string;
  identifier: string;
}

export default function AddProfile({ onComplete }: AddProfileProps) {
  const { theme } = useTheme();
  const [step, setStep] = useState(1);
  const [profileName, setProfileName] = useState('');
  const [socials, setSocials] = useState<SocialInput[]>([]);
  const [error, setError] = useState('');

  const handleAddSocial = (type: string) => {
    setSocials([...socials, { type, identifier: '' }]);
  };

  const handleUpdateSocial = (index: number, identifier: string) => {
    const newSocials = [...socials];
    newSocials[index].identifier = identifier;
    setSocials(newSocials);
  };

  const handleRemoveSocial = (index: number) => {
    setSocials(socials.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    try {
      setError('');
      const workspaceId = localStorage.getItem('selectedWorkspaceId');
      if (!workspaceId) {
        setError('No workspace selected');
        return;
      }

      if (!profileName.trim()) {
        setError('Profile name is required');
        return;
      }

      // Filter out socials with empty identifiers
      const validSocials = socials.filter(s => s.identifier.trim() !== '');

      await createProfile({
        name: profileName.trim(),
        workspace_id: workspaceId,
        socials: validSocials
      });

      onComplete();
    } catch (error) {
      console.error('Failed to create profile:', error);
      setError('Failed to create profile. Please try again.');
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className={`${theme === 'dark' ? 'bg-gray-800' : 'bg-white'} rounded-lg shadow-xl max-w-md w-full p-6 relative`}>
        <button
          onClick={onComplete}
          className={`absolute top-4 right-4 p-1 rounded-full ${
            theme === 'dark' ? 'hover:bg-gray-700' : 'hover:bg-gray-100'
          }`}
        >
          <X className="w-5 h-5" />
        </button>

        <div className="mb-8">
          <h2 className={`text-xl font-semibold ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>
            {step === 1 ? 'Ajouter un profil' : 'Ajouter des réseaux sociaux'}
          </h2>
          <div className="flex mt-4">
            <div className={`h-1 flex-1 rounded ${step === 1 ? 'bg-blue-500' : 'bg-gray-300'}`} />
            <div className={`h-1 flex-1 rounded ml-2 ${step === 2 ? 'bg-blue-500' : 'bg-gray-300'}`} />
          </div>
        </div>

        {error && (
          <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
            {error}
          </div>
        )}

        {step === 1 ? (
          <div>
            <div className="mb-6">
              <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-gray-300' : 'text-gray-700'} mb-2`}>
                Nom du profil
              </label>
              <input
                type="text"
                value={profileName}
                onChange={(e) => setProfileName(e.target.value)}
                className={`w-full px-3 py-2 rounded-md border ${
                  theme === 'dark' 
                    ? 'bg-gray-700 border-gray-600 text-white' 
                    : 'bg-white border-gray-300 text-gray-900'
                } focus:ring-2 focus:ring-blue-500 focus:border-transparent`}
                placeholder="Entrez le nom du profil"
              />
            </div>
            <button
              onClick={() => setStep(2)}
              disabled={!profileName.trim()}
              className={`w-full flex items-center justify-center px-4 py-2 rounded-md ${
                profileName.trim() 
                  ? 'bg-blue-500 hover:bg-blue-600 text-white' 
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              Suivant
              <ArrowRight className="w-4 h-4 ml-2" />
            </button>
          </div>
        ) : (
          <div>
            <div className="space-y-4 mb-6">
              {socials.map((social, index) => (
                <div key={index} className="flex items-center space-x-2">
                  <input
                    type="text"
                    value={social.identifier}
                    onChange={(e) => handleUpdateSocial(index, e.target.value)}
                    className={`flex-1 px-3 py-2 rounded-md border ${
                      theme === 'dark' 
                        ? 'bg-gray-700 border-gray-600 text-white' 
                        : 'bg-white border-gray-300 text-gray-900'
                    } focus:ring-2 focus:ring-blue-500 focus:border-transparent`}
                    placeholder={`Entrez l'identifiant ${social.type}`}
                  />
                  <button
                    onClick={() => handleRemoveSocial(index)}
                    className="p-2 text-red-500 hover:bg-red-100 rounded-md"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ))}

              <div className="flex flex-wrap gap-2">
                {['twitter', 'instagram', 'facebook', 'linkedin'].filter(
                  type => !socials.some(s => s.type === type)
                ).map((type) => (
                  <button
                    key={type}
                    onClick={() => handleAddSocial(type)}
                    className={`flex items-center px-3 py-2 rounded-md ${
                      theme === 'dark' 
                        ? 'bg-gray-700 hover:bg-gray-600' 
                        : 'bg-gray-100 hover:bg-gray-200'
                    }`}
                  >
                    {type === 'twitter' && <Twitter className="w-4 h-4 mr-2" />}
                    {type === 'instagram' && <InstagramIcon className="w-4 h-4 mr-2" />}
                    {type === 'facebook' && <Facebook className="w-4 h-4 mr-2" />}
                    {type === 'linkedin' && <Linkedin className="w-4 h-4 mr-2" />}
                    Ajouter {type.charAt(0).toUpperCase() + type.slice(1)}
                  </button>
                ))}
              </div>
            </div>

            <div className="flex space-x-3">
              <button
                onClick={() => setStep(1)}
                className={`flex-1 px-4 py-2 rounded-md ${
                  theme === 'dark' 
                    ? 'bg-gray-700 hover:bg-gray-600' 
                    : 'bg-gray-100 hover:bg-gray-200'
                }`}
              >
                Retour
              </button>
              <button
                onClick={handleSubmit}
                className="flex-1 px-4 py-2 rounded-md bg-blue-500 hover:bg-blue-600 text-white"
              >
                Créer le profil
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}