import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { SearchInput } from '../../ui/input';
import { Plus, Compass, Users, Loader2 } from 'lucide-react';
import { SocialGroup } from '../../../types';
import { GroupCard } from './GroupCard';
import { CreateGroupModal } from './CreateGroupModal';
import { useToast } from '../../../context/ToastContext';
import { groupService } from '../../../services/groupService';
import { logger } from '@/utils/logger';

interface GroupsViewProps {
  onOpenGroup: (id: string) => void;
}

export const GroupsView: React.FC<GroupsViewProps> = ({ onOpenGroup }) => {
  const { addToast } = useToast();
  const [activeTab, setActiveTab] = useState<'my_groups' | 'discover'>(
    'my_groups',
  );
  const [search, setSearch] = useState('');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [groups, setGroups] = useState<SocialGroup[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadGroups = async () => {
    try {
      setLoading(true);
      const res = await groupService.list();
      setGroups(res.groups);
    } catch (e) {
      logger.error('Failed to load groups', {
        error: e instanceof Error ? e.message : String(e),
        stack: e instanceof Error ? e.stack : undefined,
      });
      addToast('Failed to load groups', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (data: any) => {
    try {
      const newGroup = await groupService.create(data);
      setGroups([newGroup, ...groups]);
      addToast('Group created successfully', 'success');
    } catch (e) {
      addToast('Failed to create group', 'error');
    }
  };

  const handleJoin = async (id: string) => {
    try {
      await groupService.join(id);
      setGroups(
        groups.map((g) =>
          g.id === id
            ? { ...g, userRole: 'member', members: g.members + 1 }
            : g,
        ),
      );
      addToast('Joined group', 'success');
    } catch (e) {
      addToast('Failed to join group', 'error');
    }
  };

  const handleLeave = async (id: string) => {
    try {
      await groupService.leave(id);
      setGroups(
        groups.map((g) =>
          g.id === id ? { ...g, userRole: 'none', members: g.members - 1 } : g,
        ),
      );
      addToast('Left group', 'info');
    } catch (e) {
      addToast('Failed to leave group', 'error');
    }
  };

  const filteredGroups = groups.filter((g) => {
    const matchesSearch = g.name.toLowerCase().includes(search.toLowerCase());
    if (activeTab === 'my_groups')
      return matchesSearch && g.userRole !== 'none';
    return matchesSearch && g.userRole === 'none'; // Simple 'discover' logic
  });

  return (
    <div className="space-y-6 animate-fadeIn pb-20">
      <div className="flex flex-col md:flex-row justify-between items-end border-b border-kodo-steel/50 pb-6 gap-4">
        <div>
          <h2 className="text-3xl font-display font-bold text-white mb-2">
            COMMUNITIES
          </h2>
          <p className="text-gray-400 font-mono text-sm">
            Connect with producers, labels, and fans.
          </p>
        </div>
        <Button
          variant="primary"
          icon={<Plus className="w-4 h-4" />}
          onClick={() => setShowCreateModal(true)}
        >
          CREATE GROUP
        </Button>
      </div>

      <div className="flex flex-col md:flex-row gap-4 items-center bg-kodo-ink/50 p-4 rounded-xl border border-kodo-steel/50">
        <div className="flex bg-kodo-void rounded-lg p-1 border border-kodo-steel">
          <button
            onClick={() => setActiveTab('my_groups')}
            className={`flex items-center gap-2 px-4 py-2 rounded text-sm font-bold transition-colors ${activeTab === 'my_groups' ? 'bg-kodo-slate text-white' : 'text-gray-400 hover:text-white'}`}
          >
            <Users className="w-4 h-4" /> My Groups
          </button>
          <button
            onClick={() => setActiveTab('discover')}
            className={`flex items-center gap-2 px-4 py-2 rounded text-sm font-bold transition-colors ${activeTab === 'discover' ? 'bg-kodo-slate text-white' : 'text-gray-400 hover:text-white'}`}
          >
            <Compass className="w-4 h-4" /> Discover
          </button>
        </div>
        <div className="w-full md:w-96">
          <SearchInput
            placeholder="Search communities..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
      </div>

      {loading ? (
        <div className="flex justify-center py-20">
          <Loader2 className="w-10 h-10 text-kodo-cyan animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredGroups.length > 0 ? (
            filteredGroups.map((group) => (
              <GroupCard
                key={group.id}
                group={group}
                onClick={() => onOpenGroup(group.id)}
                isMember={group.userRole !== 'none'}
                onJoin={() => handleJoin(group.id)}
                onLeave={() => handleLeave(group.id)}
              />
            ))
          ) : (
            <div className="col-span-full text-center py-20 text-gray-500">
              <Users className="w-16 h-16 mx-auto mb-4 opacity-30" />
              <p>No groups found. Try searching or create your own.</p>
            </div>
          )}
        </div>
      )}

      {showCreateModal && (
        <CreateGroupModal
          onClose={() => setShowCreateModal(false)}
          onCreate={handleCreate}
        />
      )}
    </div>
  );
};
