'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { MoreHorizontal, Plus, RefreshCw, Search } from 'lucide-react';
import {
  createDiagnosticsClient,
  type DebugSession,
  type CreateSessionRequest,
} from '@/lib/diagnostics-client';

const statusColors: Record<string, string> = {
  pending: 'bg-yellow-500',
  active: 'bg-green-500',
  paused: 'bg-orange-500',
  completed: 'bg-blue-500',
  cancelled: 'bg-red-500',
};

export default function DebugSessionsPage() {
  const [sessions, setSessions] = useState<DebugSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  // Helper to get auth token from localStorage
  const getAuthToken = () => {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('admin_access_token');
  };

  // New session form state
  const [newSession, setNewSession] = useState<CreateSessionRequest>({
    targetUserId: '',
    targetDeviceId: '',
    collectionLevel: 'standard' as const,
    maxDurationMinutes: 60,
    captureLogs: true,
    captureNetwork: true,
    captureScreenshots: false,
    screenshotOnError: true,
  });

  const client = useMemo(
    () =>
      createDiagnosticsClient({
        baseUrl: process.env.NEXT_PUBLIC_PLATFORM_SERVICE_URL || 'http://localhost:4003',
        productId: 'lysnrai',
        getAuthToken,
      }),
    []
  );

  const fetchSessions = useCallback(async () => {
    setLoading(true);
    try {
      const result = await client.querySessions({
        productId: 'lysnrai',
        status: statusFilter === 'all' ? undefined : statusFilter,
      });
      setSessions(result.sessions);
    } catch (error) {
      console.error('Failed to fetch sessions:', error);
    } finally {
      setLoading(false);
    }
  }, [client, statusFilter]);

  useEffect(() => {
    void fetchSessions();
    // Auto-refresh every 5 seconds
    const interval = setInterval(() => {
      void fetchSessions();
    }, 5000);
    return () => clearInterval(interval);
  }, [fetchSessions]);

  const handleCreateSession = async () => {
    try {
      await client.createSession(newSession);
      setIsCreateModalOpen(false);
      fetchSessions();
      // Reset form
      setNewSession({
        targetUserId: '',
        targetDeviceId: '',
        collectionLevel: 'standard',
        maxDurationMinutes: 60,
        captureLogs: true,
        captureNetwork: true,
        captureScreenshots: false,
        screenshotOnError: true,
      });
    } catch (error) {
      console.error('Failed to create session:', error);
    }
  };

  const filteredSessions = sessions.filter(session => {
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        session.id.toLowerCase().includes(query) ||
        session.targetUserId?.toLowerCase().includes(query) ||
        session.targetDeviceId?.toLowerCase().includes(query)
      );
    }
    return true;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Debug Sessions</h1>
          <p className="text-muted-foreground">Remote diagnostics and debug tracing sessions</p>
        </div>
        <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              New Session
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>Create Debug Session</DialogTitle>
              <DialogDescription>
                Start a remote debug session to collect logs, traces, and screenshots from a target
                device.
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="userId">Target User ID</Label>
                  <Input
                    id="userId"
                    value={newSession.targetUserId}
                    onChange={e => setNewSession({ ...newSession, targetUserId: e.target.value })}
                    placeholder="user_123"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="deviceId">Target Device ID</Label>
                  <Input
                    id="deviceId"
                    value={newSession.targetDeviceId}
                    onChange={e => setNewSession({ ...newSession, targetDeviceId: e.target.value })}
                    placeholder="device_abc"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="collectionLevel">Collection Level</Label>
                <Select
                  value={newSession.collectionLevel}
                  onValueChange={(value: 'standard' | 'debug' | 'trace') =>
                    setNewSession({ ...newSession, collectionLevel: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="standard">Standard</SelectItem>
                    <SelectItem value="debug">Debug</SelectItem>
                    <SelectItem value="trace">Trace</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="duration">Duration (minutes)</Label>
                <Input
                  id="duration"
                  type="number"
                  min={5}
                  max={1440}
                  value={newSession.maxDurationMinutes}
                  onChange={e =>
                    setNewSession({ ...newSession, maxDurationMinutes: parseInt(e.target.value) })
                  }
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="flex items-center space-x-2">
                  <Switch
                    id="captureLogs"
                    checked={newSession.captureLogs}
                    onCheckedChange={checked =>
                      setNewSession({ ...newSession, captureLogs: checked })
                    }
                  />
                  <Label htmlFor="captureLogs">Capture Logs</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="captureNetwork"
                    checked={newSession.captureNetwork}
                    onCheckedChange={checked =>
                      setNewSession({ ...newSession, captureNetwork: checked })
                    }
                  />
                  <Label htmlFor="captureNetwork">Capture Network</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="captureScreenshots"
                    checked={newSession.captureScreenshots}
                    onCheckedChange={checked =>
                      setNewSession({ ...newSession, captureScreenshots: checked })
                    }
                  />
                  <Label htmlFor="captureScreenshots">Screenshots</Label>
                </div>
                <div className="flex items-center space-x-2">
                  <Switch
                    id="screenshotOnError"
                    checked={newSession.screenshotOnError}
                    onCheckedChange={checked =>
                      setNewSession({ ...newSession, screenshotOnError: checked })
                    }
                  />
                  <Label htmlFor="screenshotOnError">Screenshot on Error</Label>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsCreateModalOpen(false)}>
                Cancel
              </Button>
              <Button onClick={handleCreateSession}>Start Session</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle>Sessions</CardTitle>
            <div className="flex items-center gap-2">
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  type="search"
                  placeholder="Search sessions..."
                  className="pl-8 w-[250px]"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                />
              </div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-[130px]">
                  <SelectValue placeholder="Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="paused">Paused</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                  <SelectItem value="cancelled">Cancelled</SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline" size="icon" onClick={fetchSessions}>
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Session ID</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>User</TableHead>
                <TableHead>Device</TableHead>
                <TableHead>Level</TableHead>
                <TableHead>Duration</TableHead>
                <TableHead>Started</TableHead>
                <TableHead className="w-[50px]"></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8">
                    Loading...
                  </TableCell>
                </TableRow>
              ) : filteredSessions.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                    No sessions found
                  </TableCell>
                </TableRow>
              ) : (
                filteredSessions.map(session => (
                  <TableRow key={session.id}>
                    <TableCell className="font-mono text-sm">{session.id}</TableCell>
                    <TableCell>
                      <Badge
                        variant="secondary"
                        className={`${statusColors[session.status]} text-white`}
                      >
                        {session.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{session.targetUserId || '-'}</TableCell>
                    <TableCell>{session.targetDeviceId || '-'}</TableCell>
                    <TableCell className="capitalize">{session.collectionLevel}</TableCell>
                    <TableCell>{session.maxDurationMinutes} min</TableCell>
                    <TableCell>
                      {session.startedAt ? new Date(session.startedAt).toLocaleString() : '-'}
                    </TableCell>
                    <TableCell>
                      <Button variant="ghost" size="icon">
                        <MoreHorizontal className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
