"use client";

import { useState, useEffect, useCallback } from 'react';
import { useApi } from '@/hooks/use-api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { RefreshCw, Users, Lock, Unlock, ArrowRight, ServerCrash, Radio } from 'lucide-react';
import Link from 'next/link';
import { formatDistanceToNow } from 'date-fns';

export default function ConferenceList() {
    const [conferences, setConferences] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const apiFetch = useApi();

    const fetchConferences = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            // Acting as an unauthenticated user, so no auth token is sent.
            // This assumes the endpoint is public.
            const res = await apiFetch(`${process.env.NEXT_PUBLIC_API_URL}/conferences`);
            if (!res.ok) {
                const errorData = await res.json();
                if (res.status === 401) {
                    throw new Error("Unauthorized: Please log in to view conferences.");
                }
                throw new Error(errorData.error || 'Failed to fetch conferences');
            }
            const data = await res.json();
            setConferences(Array.isArray(data) ? data : []);
        } catch (err) {
            if (err.message !== 'Unauthorized') {
                console.error("Failed to fetch conferences", err);
            }
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [apiFetch]);

    useEffect(() => {
        fetchConferences();
        const interval = setInterval(fetchConferences, 15000); // Refresh every 15 seconds
        return () => clearInterval(interval);
    }, [fetchConferences]);

    return (
        <div className="container py-12 px-4">
            <div className="max-w-4xl mx-auto">
                <div className="text-center mb-12">
                    <h1 className="text-4xl md:text-5xl font-bold text-white mb-4 bg-gradient-to-r from-white via-green-100 to-white bg-clip-text text-transparent">
                        Active Conferences
                    </h1>
                    <p className="text-xl text-gray-300 max-w-2xl mx-auto">
                        Join a conversation or see who's currently in a conference.
                    </p>
                    <div className="flex items-center justify-center gap-4 mt-6">
                        <Button onClick={fetchConferences} disabled={loading}>
                            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
                            {loading ? 'Refreshing...' : 'Refresh'}
                        </Button>
                    </div>
                </div>

                {error && (
                    <Card className="bg-red-950/50 border-red-800 mb-8">
                        <CardContent className="flex items-center gap-3 p-4">
                            <ServerCrash className="h-5 w-5 text-red-400" />
                            <div className="text-red-100">
                                {error}
                            </div>
                        </CardContent>
                    </Card>
                )}

                {loading ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {[...Array(4)].map((_, i) => (
                            <Card key={i} className="bg-gray-950/50 border-gray-800 p-6">
                                <Skeleton className="h-6 w-3/4 mb-4" />
                                <Skeleton className="h-4 w-1/2 mb-6" />
                                <div className="flex justify-between items-center">
                                    <Skeleton className="h-6 w-24" />
                                    <Skeleton className="h-10 w-24" />
                                </div>
                            </Card>
                        ))}
                    </div>
                ) : conferences.length > 0 ? (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {conferences.map(room => (
                            <Card key={room.conferenceId} className="group bg-gray-950/50 border-gray-800 hover:border-blue-500/50 transition-all duration-300">
                                <CardHeader>
                                    <CardTitle className="text-white text-2xl font-bold flex items-center gap-3">
                                        <Radio className="h-6 w-6 text-blue-400" />
                                        {room.conferenceId}
                                    </CardTitle>
                                    <CardDescription>
                                        {room.parties} participant(s)
                                    </CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <div className="flex justify-between items-center">
                                        <div className="flex items-center gap-4">
                                            <div className="flex items-center gap-2 text-gray-300">
                                                <Users className="h-5 w-5" />
                                                <span>{room.parties}</span>
                                            </div>
                                            <div className="flex items-center gap-2 text-gray-300">
                                                {room.locked ? <Lock className="h-5 w-5 text-red-400" /> : <Unlock className="h-5 w-5 text-green-400" />}
                                                <span>{room.locked ? 'Locked' : 'Open'}</span>
                                            </div>
                                        </div>
                                        <Button asChild variant="outline" size="sm">
                                            <Link href={`/conferences?id=${room.conferenceId}`}>
                                                View <ArrowRight className="ml-2 h-4 w-4" />
                                            </Link>
                                        </Button>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                ) : (
                    <div className="text-center py-20 text-gray-500 flex flex-col items-center justify-center border-2 border-dashed border-gray-800 rounded-lg">
                        <Radio className="mx-auto h-16 w-16 mb-4 text-gray-600" />
                        <h3 className="text-2xl font-semibold text-gray-300">No Active Conferences</h3>
                        <p className="mt-2">When a conference starts, it will appear here.</p>
                    </div>
                )}
            </div>
        </div>
    );
}
