import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Users,
  Plus,
  Calendar,
  Clock,
  Play,
  UserPlus,
  LogOut,
  Crown,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';
import { format } from 'date-fns';
import type { BodyDoublingSession } from '@shared/schema';

interface SessionWithParticipants extends BodyDoublingSession {
  participantCount: number;
  isParticipant: boolean;
  host: { username: string };
}

const sessionTypes = [
  { id: 'focus', icon: '🎯' },
  { id: 'brainstorm', icon: '💡' },
  { id: 'admin', icon: '📋' },
  { id: 'creative', icon: '🎨' },
];

export function BodyDoublingLobby() {
  const { t } = useTranslation();
  const { settings } = useADHDMode();
  const queryClient = useQueryClient();

  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [newSession, setNewSession] = useState({
    title: '',
    sessionType: 'focus',
    durationMinutes: 50,
    startsAt: '',
  });

  // Fetch sessions
  const { data: sessions = [], isLoading } = useQuery<SessionWithParticipants[]>({
    queryKey: ['/api/sessions'],
  });

  // Create session mutation
  const createMutation = useMutation({
    mutationFn: async (data: typeof newSession) => {
      const res = await fetch('/api/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          ...data,
          startsAt: new Date(data.startsAt).toISOString(),
        }),
      });
      if (!res.ok) throw new Error('Failed to create session');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/sessions'] });
      setCreateDialogOpen(false);
      setNewSession({
        title: '',
        sessionType: 'focus',
        durationMinutes: 50,
        startsAt: '',
      });
    },
  });

  // Join session mutation
  const joinMutation = useMutation({
    mutationFn: async (sessionId: string) => {
      const res = await fetch(`/api/sessions/${sessionId}/join`, {
        method: 'POST',
        credentials: 'include',
      });
      if (!res.ok) throw new Error('Failed to join session');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/sessions'] });
    },
  });

  // Leave session mutation
  const leaveMutation = useMutation({
    mutationFn: async (sessionId: string) => {
      const res = await fetch(`/api/sessions/${sessionId}/leave`, {
        method: 'POST',
        credentials: 'include',
      });
      if (!res.ok) throw new Error('Failed to leave session');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/sessions'] });
    },
  });

  const handleCreate = () => {
    createMutation.mutate(newSession);
  };

  const upcomingSessions = sessions.filter((s) => s.status === 'scheduled');
  const activeSessions = sessions.filter((s) => s.status === 'active');

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-xl sm:text-2xl font-bold flex items-center gap-2">
            <Users className="h-5 w-5 sm:h-6 sm:w-6 text-primary" />
            {t('adhd.bodyDoubling.title')}
          </h2>
          <p className="text-sm sm:text-base text-muted-foreground">
            {t('adhd.bodyDoubling.description')}
          </p>
        </div>

        <Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button className={settings.largerTargets ? 'h-12 px-6' : ''}>
              <Plus className="h-4 w-4 mr-2" />
              {t('adhd.bodyDoubling.createSession')}
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('adhd.bodyDoubling.newSession')}</DialogTitle>
              <DialogDescription>
                {t('adhd.bodyDoubling.newSessionDesc')}
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4">
              <div>
                <Label htmlFor="title">{t('adhd.bodyDoubling.sessionTitle')}</Label>
                <Input
                  id="title"
                  value={newSession.title}
                  onChange={(e) => setNewSession({ ...newSession, title: e.target.value })}
                  placeholder={t('adhd.bodyDoubling.titlePlaceholder')}
                />
              </div>

              <div>
                <Label>{t('adhd.bodyDoubling.sessionType')}</Label>
                <Select
                  value={newSession.sessionType}
                  onValueChange={(value) => setNewSession({ ...newSession, sessionType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {sessionTypes.map((type) => (
                      <SelectItem key={type.id} value={type.id}>
                        {type.icon} {t(`adhd.bodyDoubling.types.${type.id}`)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="startsAt">{t('adhd.bodyDoubling.startTime')}</Label>
                  <Input
                    id="startsAt"
                    type="datetime-local"
                    value={newSession.startsAt}
                    onChange={(e) => setNewSession({ ...newSession, startsAt: e.target.value })}
                  />
                </div>
                <div>
                  <Label>{t('adhd.bodyDoubling.duration')}</Label>
                  <Select
                    value={newSession.durationMinutes.toString()}
                    onValueChange={(value) => setNewSession({ ...newSession, durationMinutes: parseInt(value) })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="25">25 min</SelectItem>
                      <SelectItem value="50">50 min</SelectItem>
                      <SelectItem value="90">90 min</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <Button
                onClick={handleCreate}
                disabled={!newSession.title || !newSession.startsAt || createMutation.isPending}
                className="w-full"
              >
                {createMutation.isPending ? t('common.creating') : t('adhd.bodyDoubling.create')}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Active Sessions */}
      {activeSessions.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold mb-3 flex items-center gap-2">
            <Play className="h-5 w-5 text-green-500" />
            {t('adhd.bodyDoubling.activeSessions')}
          </h3>
          <div className="grid gap-4 md:grid-cols-2">
            {activeSessions.map((session) => (
              <SessionCard
                key={session.id}
                session={session}
                onJoin={() => joinMutation.mutate(session.id)}
                onLeave={() => leaveMutation.mutate(session.id)}
                isJoining={joinMutation.isPending}
                isLeaving={leaveMutation.isPending}
              />
            ))}
          </div>
        </div>
      )}

      {/* Upcoming Sessions */}
      <div>
        <h3 className="text-lg font-semibold mb-3 flex items-center gap-2">
          <Calendar className="h-5 w-5 text-primary" />
          {t('adhd.bodyDoubling.upcomingSessions')}
        </h3>
        {upcomingSessions.length === 0 ? (
          <Card>
            <CardContent className="flex flex-col items-center justify-center py-8">
              <Users className="h-12 w-12 text-muted-foreground/50 mb-4" />
              <p className="text-muted-foreground text-center">
                {t('adhd.bodyDoubling.noSessions')}
              </p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            <AnimatePresence>
              {upcomingSessions.map((session, index) => (
                <motion.div
                  key={session.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                >
                  <SessionCard
                    session={session}
                    onJoin={() => joinMutation.mutate(session.id)}
                    onLeave={() => leaveMutation.mutate(session.id)}
                    isJoining={joinMutation.isPending}
                    isLeaving={leaveMutation.isPending}
                  />
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        )}
      </div>
    </div>
  );
}

// Session Card Component
function SessionCard({
  session,
  onJoin,
  onLeave,
  isJoining,
  isLeaving,
}: {
  session: SessionWithParticipants;
  onJoin: () => void;
  onLeave: () => void;
  isJoining: boolean;
  isLeaving: boolean;
}) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();

  const sessionType = sessionTypes.find((t) => t.id === session.sessionType);
  const isActive = session.status === 'active';

  return (
    <Card className={`
      ${isActive ? 'border-green-500/50 bg-green-500/5' : ''}
      ${session.isParticipant ? 'ring-2 ring-primary/50' : ''}
    `}>
      <CardHeader className="pb-2">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-2">
            <span className="text-2xl">{sessionType?.icon}</span>
            <div>
              <CardTitle className="text-base">{session.title}</CardTitle>
              <CardDescription className="flex items-center gap-1">
                <Crown className="h-3 w-3" />
                {session.host?.username}
              </CardDescription>
            </div>
          </div>
          {isActive && (
            <Badge variant="default" className="bg-green-500">
              {t('adhd.bodyDoubling.live')}
            </Badge>
          )}
        </div>
      </CardHeader>
      <CardContent>
        <div className="flex items-center gap-4 text-sm text-muted-foreground mb-4">
          <span className="flex items-center gap-1">
            <Calendar className="h-4 w-4" />
            {format(new Date(session.startsAt), 'MMM d, HH:mm')}
          </span>
          <span className="flex items-center gap-1">
            <Clock className="h-4 w-4" />
            {session.durationMinutes} min
          </span>
          <span className="flex items-center gap-1">
            <Users className="h-4 w-4" />
            {session.participantCount}/{session.maxParticipants}
          </span>
        </div>

        {session.isParticipant ? (
          <Button
            variant="outline"
            onClick={onLeave}
            disabled={isLeaving}
            className={`w-full ${settings.largerTargets ? 'h-11' : ''}`}
          >
            <LogOut className="h-4 w-4 mr-2" />
            {t('adhd.bodyDoubling.leave')}
          </Button>
        ) : (
          <Button
            onClick={onJoin}
            disabled={isJoining || session.participantCount >= session.maxParticipants}
            className={`w-full ${settings.largerTargets ? 'h-11' : ''}`}
          >
            <UserPlus className="h-4 w-4 mr-2" />
            {t('adhd.bodyDoubling.join')}
          </Button>
        )}
      </CardContent>
    </Card>
  );
}
