import React, { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import {
  ArrowLeft,
  Users,
  Lock,
  Globe,
  Plus,
  LogOut,
  Settings,
  Loader2,
} from 'lucide-react';
import { SocialGroup } from '../../../types';
import { useToast } from '../../../context/ToastContext';
import { FeedView } from '../FeedView';
import { groupService } from '../../../services/groupService';
import { logger } from '@/utils/logger';

interface GroupDetailViewProps {
  groupId: string;
  onBack: () => void;
}

interface ExtendedGroup extends SocialGroup {
  membersList: any[];
  events: any[];
}

export const GroupDetailView: React.FC<GroupDetailViewProps> = ({
  groupId,
  onBack,
}) => {
  const { addToast } = useToast();
  const [group, setGroup] = useState<ExtendedGroup | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'feed' | 'members' | 'events'>(
    'feed',
  );

  useEffect(() => {
    const loadGroup = async () => {
      setLoading(true);
      try {
        const res = await groupService.get(groupId);
        setGroup({
          ...res.group,
          membersList: res.membersList || [],
          events: res.events || [],
        });
      } catch (e) {
        logger.error('Failed to load group details', {
          error: e instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined,
          groupId,
        });
        addToast('Failed to load group details', 'error');
      } finally {
        setLoading(false);
      }
    };
    loadGroup();
  }, [groupId]);

  const handleJoin = async () => {
    if (!group) return;
    await groupService.join(group.id);
    setGroup({ ...group, userRole: 'member', members: group.members + 1 });
    addToast('Joined group!', 'success');
  };

  const handleLeave = async () => {
    if (!group) return;
    await groupService.leave(group.id);
    setGroup({ ...group, userRole: 'none', members: group.members - 1 });
    addToast('Left group', 'info');
  };

  if (loading)
    return (
      <div className="flex justify-center py-20">
        <Loader2 className="w-10 h-10 text-kodo-cyan animate-spin" />
      </div>
    );
  if (!group)
    return (
      <div className="text-center py-20 text-gray-500">Group not found</div>
    );

  return (
    <div className="animate-fadeIn space-y-6 pb-20">
      {/* Header */}
      <div className="relative rounded-2xl overflow-hidden bg-kodo-graphite border border-kodo-steel">
        <div className="h-64 bg-gray-900 relative">
          <img
            src={group.coverUrl}
            className="w-full h-full object-cover opacity-80"
          />
          <div className="absolute top-4 left-4">
            <Button
              variant="ghost"
              className="bg-black/50 backdrop-blur text-white hover:bg-black/70"
              onClick={onBack}
            >
              <ArrowLeft className="w-4 h-4 mr-2" /> Back
            </Button>
          </div>
          <div className="absolute bottom-4 right-4 flex gap-2">
            {group.userRole === 'admin' && (
              <Button
                variant="secondary"
                size="sm"
                className="bg-black/50 backdrop-blur border-none hover:bg-black/70"
              >
                <Settings className="w-4 h-4 mr-2" /> Settings
              </Button>
            )}
            {group.userRole !== 'none' ? (
              <Button
                variant="ghost"
                size="sm"
                className="bg-black/50 backdrop-blur text-red-400 hover:bg-red-500/20 border-none"
                onClick={handleLeave}
              >
                <LogOut className="w-4 h-4 mr-2" /> Leave
              </Button>
            ) : (
              <Button variant="primary" size="sm" onClick={handleJoin}>
                <Plus className="w-4 h-4 mr-2" /> Join Group
              </Button>
            )}
          </div>
        </div>

        <div className="p-6 md:p-8">
          <div className="flex flex-col md:flex-row justify-between items-start gap-4">
            <div>
              <div className="flex items-center gap-3 mb-2">
                <h1 className="text-3xl font-display font-bold text-white">
                  {group.name}
                </h1>
                <span
                  className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase border flex items-center gap-1 ${group.isPrivate ? 'border-kodo-gold text-kodo-gold' : 'border-kodo-cyan text-kodo-cyan'}`}
                >
                  {group.isPrivate ? (
                    <Lock className="w-3 h-3" />
                  ) : (
                    <Globe className="w-3 h-3" />
                  )}
                  {group.isPrivate ? 'Private' : 'Public'}
                </span>
              </div>
              <p className="text-gray-400 max-w-2xl leading-relaxed">
                {group.description}
              </p>
            </div>

            <div className="flex gap-6 text-sm text-gray-400 font-mono bg-kodo-ink/50 p-4 rounded-xl border border-kodo-steel/30">
              <div className="text-center">
                <div className="font-bold text-white text-lg">
                  {group.members.toLocaleString()}
                </div>
                <div className="text-xs uppercase">Members</div>
              </div>
              <div className="w-px bg-kodo-steel/50"></div>
              <div className="text-center">
                <div className="font-bold text-white text-lg">124</div>
                <div className="text-xs uppercase">Posts</div>
              </div>
              <div className="w-px bg-kodo-steel/50"></div>
              <div className="text-center">
                <div className="font-bold text-white text-lg">
                  {group.events.length}
                </div>
                <div className="text-xs uppercase">Events</div>
              </div>
            </div>
          </div>
        </div>

        {/* Navigation */}
        <div className="px-6 md:px-8 border-t border-kodo-steel/50 flex gap-6 overflow-x-auto">
          {['feed', 'members', 'events'].map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab as any)}
              className={`py-4 text-sm font-bold uppercase tracking-wider border-b-2 transition-colors ${activeTab === tab ? 'text-white border-kodo-cyan' : 'text-gray-500 border-transparent hover:text-gray-300'}`}
            >
              {tab}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        <div className="lg:col-span-8">
          {activeTab === 'feed' && <FeedView />}

          {activeTab === 'members' && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {group.membersList.map((member) => (
                <div
                  key={member.id}
                  className="flex items-center gap-4 p-4 bg-kodo-ink rounded-lg border border-kodo-steel hover:border-kodo-cyan/30 transition-colors"
                >
                  <img src={member.avatar} className="w-12 h-12 rounded-full" />
                  <div className="flex-1">
                    <div className="font-bold text-white">
                      {member.username}
                    </div>
                    {member.role && (
                      <span className="text-[10px] bg-kodo-slate px-1.5 py-0.5 rounded text-gray-400">
                        {member.role}
                      </span>
                    )}
                  </div>
                  <Button variant="ghost" size="sm">
                    View
                  </Button>
                </div>
              ))}
              {/* Placeholder for more members */}
              <div className="col-span-full text-center py-8 text-gray-500 text-sm">
                + {Math.max(0, group.members - group.membersList.length)} others
              </div>
            </div>
          )}

          {activeTab === 'events' && (
            <div className="space-y-4">
              {group.events.map((event) => (
                <Card
                  key={event.id}
                  variant="default"
                  className="flex items-center gap-6"
                >
                  <div className="text-center p-3 bg-kodo-slate rounded-lg min-w-[80px]">
                    <div className="text-xs text-kodo-cyan uppercase font-bold">
                      {event.date.split(' ')[0]}
                    </div>
                    <div className="text-2xl font-bold text-white">
                      {event.date.split(' ')[1].replace(',', '')}
                    </div>
                  </div>
                  <div className="flex-1">
                    <h3 className="text-lg font-bold text-white">
                      {event.title}
                    </h3>
                    <div className="flex items-center gap-2 text-gray-400 text-sm mt-1">
                      <Users className="w-4 h-4" /> {event.attendees} Attending
                    </div>
                  </div>
                  <Button variant="secondary">RSVP</Button>
                </Card>
              ))}
            </div>
          )}
        </div>

        <div className="lg:col-span-4 space-y-6">
          <Card variant="default">
            <h3 className="font-bold text-white mb-4 uppercase text-xs tracking-wider">
              About
            </h3>
            <p className="text-sm text-gray-400 mb-4">
              Created Aug 2022
              <br />
              Located in Tokyo, JP
            </p>
            <div className="flex flex-wrap gap-2">
              {['Synthesizers', 'Hardware', 'Eurorack', 'Music'].map((tag) => (
                <span
                  key={tag}
                  className="px-2 py-1 bg-kodo-ink border border-kodo-steel rounded text-xs text-gray-400"
                >
                  #{tag}
                </span>
              ))}
            </div>
          </Card>

          <Card variant="gaming">
            <h3 className="font-bold text-white mb-4 uppercase text-xs tracking-wider">
              Group Admins
            </h3>
            <div className="flex -space-x-2 overflow-hidden mb-4">
              {group.membersList
                .filter((m) => m.role)
                .map((m) => (
                  <img
                    key={m.id}
                    src={m.avatar}
                    className="inline-block h-8 w-8 rounded-full ring-2 ring-kodo-graphite"
                    title={m.username}
                  />
                ))}
            </div>
            <Button variant="ghost" size="sm" className="w-full text-xs">
              Message Admins
            </Button>
          </Card>
        </div>
      </div>
    </div>
  );
};
