// src/app/dashboard/page.tsx
'use client'

import { Plus, Twitter, InstagramIcon, Facebook, Linkedin } from 'lucide-react';
import { useState, useEffect } from 'react';
import AddProfile from '@/components/profiles/addProfile';
import { useTheme } from '@/contexts/themecontext';
import { getProfilesByWorkspace, type Profile } from '@/lib/api/core';

export default function DashboardPage() {
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [profiles, setProfiles] = useState<Profile[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const { theme } = useTheme();

  useEffect(() => {
    const fetchProfiles = async () => {
      try {
        const workspaceId = localStorage.getItem('selectedWorkspaceId');
        if (!workspaceId) return;
        
        const fetchedProfiles = await getProfilesByWorkspace(workspaceId);
        setProfiles(fetchedProfiles);
      } catch (error) {
        console.error('Failed to fetch profiles:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchProfiles();
  }, []);

  const handleNewProfileClick = () => {
    setShowOnboarding(true);
  };

  const handleOnboardingComplete = () => {
    setShowOnboarding(false);
    // Refresh profiles after creating a new one
    const workspaceId = localStorage.getItem('selectedWorkspaceId');
    if (workspaceId) {
      getProfilesByWorkspace(workspaceId).then(setProfiles);
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-full">
        <div className="w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="p-4">
      {showOnboarding && <AddProfile onComplete={handleOnboardingComplete} />}

      <div className="flex items-center justify-between mb-6">
        <h1 className={`text-2xl font-bold ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>
          Tous les profils
        </h1>
      </div>

      {profiles.length === 0 ? (
        <div className={`text-center py-12 ${theme === 'dark' ? 'text-gray-400' : 'text-gray-600'}`}>
          <p className="text-lg mb-4">Aucun profil</p>
          <button
            onClick={handleNewProfileClick}
            className={`inline-flex items-center px-4 py-2 rounded-md ${
              theme === 'dark' ? 'bg-gray-800 hover:bg-gray-700' : 'bg-gray-100 hover:bg-gray-200'
            } transition-colors`}
          >
            <Plus className="w-5 h-5 mr-2" />
            Créer un profil
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {profiles.map((profile) => (
            <ProfileCard 
              key={profile.id} 
              profile={profile} 
              theme={theme} 
            />
          ))}
          <NewProfileCard onClick={handleNewProfileClick} theme={theme} />
        </div>
      )}
    </div>
  );
}

function ProfileCard({ profile, theme }: { profile: Profile, theme: 'dark' | 'light' }) {
  const socialIcons = {
    twitter: <Twitter className="w-4 h-4 text-blue-400" />,
    instagram: <InstagramIcon className="w-4 h-4 text-pink-500" />,
    facebook: <Facebook className="w-4 h-4 text-blue-600" />,
    linkedin: <Linkedin className="w-4 h-4 text-blue-700" />
  };

  const getProfileIcon = () => {
    if (profile.socials && profile.socials.length > 0) {
      const firstSocial = profile.socials[0];
      return socialIcons[firstSocial.type as keyof typeof socialIcons] || '👤';
    }
    return '👤';
  };

  return (
    <div className={`${theme === 'dark' ? 'bg-gray-800' : 'bg-white'} rounded-lg p-4 hover:ring-2 hover:ring-blue-500/50 transition-all cursor-pointer shadow-lg`}>
      <div className="flex items-center space-x-4">
        <div className={`w-12 h-12 ${theme === 'dark' ? 'bg-gray-700' : 'bg-gray-100'} rounded-full flex items-center justify-center text-2xl`}>
          {getProfileIcon()}
        </div>
        <div>
          <h3 className={`font-medium ${theme === 'dark' ? 'text-white' : 'text-gray-900'}`}>
            {profile.name}
          </h3>
          <p className={`text-sm ${theme === 'dark' ? 'text-gray-400' : 'text-gray-600'}`}>
            @{profile.name.toLowerCase()}
          </p>
        </div>
      </div>

      <div className="mt-4">
        <div className="flex flex-wrap gap-2">
          {profile.socials?.map((social) => (
            <div 
              key={social.id}
              className={`flex items-center px-2 py-1 rounded ${
                theme === 'dark' ? 'bg-gray-700' : 'bg-gray-100'
              }`}
            >
              {socialIcons[social.type as keyof typeof socialIcons]}
              <span className="ml-1 text-sm">{social.identifier}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function NewProfileCard({ onClick, theme }: { onClick: () => void, theme: 'dark' | 'light' }) {
  return (
    <div
      className={`${theme === 'dark' ? 'bg-gray-800' : 'bg-white'} rounded-lg aspect-video p-4 flex flex-col justify-center items-center hover:ring-2 hover:ring-blue-500/50 transition-all cursor-pointer shadow-lg`}
      onClick={onClick}
    >
      <div className={`w-12 h-12 ${theme === 'dark' ? 'bg-gray-700' : 'bg-gray-100'} rounded-full flex items-center justify-center`}>
        <Plus className={`w-6 h-6 ${theme === 'dark' ? 'text-gray-500' : 'text-gray-400'}`} />
      </div>
      <p className={`text-sm ${theme === 'dark' ? 'text-gray-400' : 'text-gray-600'} mt-2`}>Ajouter un nouveau profil</p>
    </div>
  );
}