import { ReactNode } from 'react';
import { Head } from '@inertiajs/react';
import { useQuery } from '@tanstack/react-query';
import AdminLayout from '@/layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Video, Users, CheckCircle, Clock, ExternalLink, Phone, Pencil, Camera } from 'lucide-react';
import { format } from 'date-fns';

const statusBadge = (status: string) => {
  const map: Record<string, { label: string; className: string }> = {
    requested: { label: 'Requested', className: 'bg-amber-500/10 text-amber-700 border-amber-500/30 border' },
    active: { label: 'Active', className: 'bg-emerald-500/10 text-emerald-700 border-emerald-500/30 border' },
    completed: { label: 'Completed', className: 'bg-blue-500/10 text-blue-700 border-blue-500/30 border' },
    cancelled: { label: 'Cancelled', className: 'bg-destructive/10 text-destructive border-destructive/30 border' },
  };
  const s = map[status] || { label: status, className: '' };
  return <Badge className={s.className}>{s.label}</Badge>;
};

const fmtDuration = (seconds: number | null) => {
  if (!seconds) return '—';
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}m ${secs}s`;
};

const ARAssistPage = () => {
  const { data: sessions, isLoading } = useQuery({
    queryKey: ['ar-assist-sessions'],
    queryFn: async () => {
      const res = await fetch('/api/admin/ar-assist-sessions');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const activeSessions = sessions?.filter((s: any) => s.status === 'active').length || 0;
  const totalSessions = sessions?.length || 0;
  const completedSessions = sessions?.filter((s: any) => s.status === 'completed').length || 0;
  const avgDuration = (() => {
    const completed = sessions?.filter((s: any) => s.status === 'completed' && s.duration_seconds) || [];
    if (completed.length === 0) return '—';
    const avg = completed.reduce((sum: number, s: any) => sum + (s.duration_seconds || 0), 0) / completed.length;
    return `${Math.round(avg / 60)}m`;
  })();

  const kpis = [
    { label: 'Active Sessions', value: activeSessions, icon: Video, color: 'text-emerald-600' },
    { label: 'Total Sessions', value: totalSessions, icon: Users, color: 'text-primary' },
    { label: 'Completed', value: completedSessions, icon: CheckCircle, color: 'text-blue-600' },
    { label: 'Avg Duration', value: avgDuration, icon: Clock, color: 'text-amber-600' },
  ];

  const howItWorks = [
    {
      icon: Phone,
      title: 'Engineer Requests Help',
      description: "From the mobile job card, the engineer taps 'Request AR Assist' to initiate a live support session.",
    },
    {
      icon: Camera,
      title: 'Live Video + AR Overlay',
      description: "The mentor sees the engineer's camera feed in real-time and can draw annotations, arrows, and measurements directly on the live view.",
    },
    {
      icon: Pencil,
      title: 'Auto-Documentation',
      description: 'Sessions are automatically recorded and linked to the job card for compliance audit trails and future reference.',
    },
  ];

  return (
    <>
      <Head title="AR Remote Assist" />
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold text-foreground">AR Remote Assist</h1>
          <p className="text-sm text-muted-foreground">
            Live video support sessions between field engineers and remote mentors
          </p>
        </div>

        {/* KPI Cards */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {kpis.map((kpi) => (
            <Card key={kpi.label}>
              <CardContent className="py-4 flex items-center gap-3">
                <kpi.icon className={`h-5 w-5 ${kpi.color}`} />
                <div>
                  <p className="text-2xl font-bold text-foreground">{kpi.value}</p>
                  <p className="text-xs text-muted-foreground">{kpi.label}</p>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Session History */}
        <Card>
          <CardHeader>
            <CardTitle>Session History</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <p className="text-sm text-muted-foreground">Loading sessions...</p>
            ) : !sessions?.length ? (
              <p className="text-sm text-muted-foreground">No AR assist sessions yet. Sessions will appear here when engineers request remote support.</p>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead>Engineer</TableHead>
                      <TableHead>Job Ref</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Duration</TableHead>
                      <TableHead>Mentor</TableHead>
                      <TableHead>Recording</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sessions.map((session: any) => (
                      <TableRow key={session.id}>
                        <TableCell className="text-sm">{format(new Date(session.created_at), 'dd MMM yyyy HH:mm')}</TableCell>
                        <TableCell className="text-sm font-medium">{session.engineer_name || '—'}</TableCell>
                        <TableCell className="text-sm">{session.job_reference || '—'}</TableCell>
                        <TableCell>{statusBadge(session.status)}</TableCell>
                        <TableCell className="text-sm">{fmtDuration(session.duration_seconds)}</TableCell>
                        <TableCell className="text-sm">{session.mentor_name || '—'}</TableCell>
                        <TableCell>
                          {session.recording_url ? (
                            <Button variant="outline" size="sm" className="gap-1" asChild>
                              <a href={session.recording_url} target="_blank" rel="noopener noreferrer">
                                <ExternalLink className="h-3 w-3" /> View
                              </a>
                            </Button>
                          ) : (
                            <span className="text-xs text-muted-foreground">—</span>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* How It Works */}
        <div>
          <h2 className="text-lg font-semibold text-foreground mb-4">How It Works</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {howItWorks.map((step, i) => (
              <Card key={i}>
                <CardContent className="py-6 text-center space-y-3">
                  <div className="mx-auto w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center">
                    <step.icon className="h-6 w-6 text-primary" />
                  </div>
                  <h3 className="font-semibold text-foreground">
                    <span className="text-primary mr-1">{i + 1}.</span> {step.title}
                  </h3>
                  <p className="text-sm text-muted-foreground">{step.description}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>

        {/* Implementation Note */}
        <Card className="border-dashed">
          <CardContent className="py-4">
            <p className="text-sm text-muted-foreground">
              <strong>Note:</strong> This is a UI-ready scaffold. The WebRTC video streaming, canvas annotation layer, and media recording pipeline require a signalling server (via backend functions + Realtime channels) for production deployment.
            </p>
          </CardContent>
        </Card>
      </div>
    </>
  );
};

ARAssistPage.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default ARAssistPage;
