import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Video, Phone, Plus, Clock, ExternalLink } from "lucide-react";
import { toast } from "sonner";
import { format } from "date-fns";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? "";

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 "—";
  return `${Math.floor(seconds / 60)}m`;
};

const AREngineerSupport = ({ companyId }: { companyId: string }) => {
  const [showForm, setShowForm] = useState(false);
  const [engineerName, setEngineerName] = useState("");
  const [jobRef, setJobRef] = useState("");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const { data: sessions, refetch } = useQuery({
    queryKey: ["company-ar-sessions", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/ar-assist-sessions?company_id=${encodeURIComponent(companyId)}&limit=20`);
      if (!res.ok) throw new Error("Failed to load sessions");
      const data = await res.json();
      return (data?.data ?? data) as any[];
    },
  });

  const requestSession = async () => {
    if (!engineerName.trim()) {
      toast.error("Please enter the engineer's name");
      return;
    }
    setSubmitting(true);
    const res = await fetch("/api/ar-assist-sessions", {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken() },
      body: JSON.stringify({
        company_id: companyId,
        engineer_name: engineerName.trim(),
        job_reference: jobRef.trim() || null,
        notes: notes.trim() || null,
        status: "requested",
      }),
    });
    if (!res.ok) {
      toast.error("Failed to request session");
    } else {
      toast.success("AR Assist session requested");
      setEngineerName("");
      setJobRef("");
      setNotes("");
      setShowForm(false);
      refetch();
    }
    setSubmitting(false);
  };

  const activeSessions = sessions?.filter((s) => s.status === "active" || s.status === "requested") || [];

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Video className="h-5 w-5 text-primary" /> AR Remote Assist
            </CardTitle>
            <Button onClick={() => setShowForm(!showForm)} size="sm" className="gap-1">
              <Plus className="h-4 w-4" /> Request Session
            </Button>
          </div>
          <p className="text-sm text-muted-foreground">
            Connect field engineers with remote mentors for live video guidance and AR annotations
          </p>
        </CardHeader>

        {showForm && (
          <CardContent className="border-t pt-4 space-y-3">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div>
                <label className="text-sm font-medium text-foreground">Engineer Name *</label>
                <Input value={engineerName} onChange={(e) => setEngineerName(e.target.value)} placeholder="e.g. John Smith" />
              </div>
              <div>
                <label className="text-sm font-medium text-foreground">Job Reference</label>
                <Input value={jobRef} onChange={(e) => setJobRef(e.target.value)} placeholder="e.g. JOB-2024-001" />
              </div>
            </div>
            <div>
              <label className="text-sm font-medium text-foreground">Notes</label>
              <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Describe the issue..." rows={2} />
            </div>
            <div className="flex gap-2">
              <Button onClick={requestSession} disabled={submitting} className="gap-1">
                <Phone className="h-4 w-4" /> {submitting ? "Requesting..." : "Submit Request"}
              </Button>
              <Button variant="outline" onClick={() => setShowForm(false)}>Cancel</Button>
            </div>
          </CardContent>
        )}
      </Card>

      {activeSessions.length > 0 && (
        <Card className="border-emerald-500/30 bg-emerald-50 dark:bg-emerald-950/10">
          <CardContent className="py-4">
            <p className="text-sm font-medium text-foreground">
              {activeSessions.length} active/pending session{activeSessions.length !== 1 ? "s" : ""}
            </p>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="text-sm">Recent Sessions</CardTitle>
        </CardHeader>
        <CardContent>
          {!sessions?.length ? (
            <p className="text-sm text-muted-foreground">No sessions yet. Request a session to get started.</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>Recording</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sessions.map((s) => (
                    <TableRow key={s.id}>
                      <TableCell className="text-sm">{format(new Date(s.created_at), "dd MMM HH:mm")}</TableCell>
                      <TableCell className="text-sm font-medium">{s.engineer_name || "—"}</TableCell>
                      <TableCell className="text-sm">{s.job_reference || "—"}</TableCell>
                      <TableCell>{statusBadge(s.status)}</TableCell>
                      <TableCell className="text-sm">{fmtDuration(s.duration_seconds)}</TableCell>
                      <TableCell>
                        {s.recording_url ? (
                          <Button variant="outline" size="sm" asChild>
                            <a href={s.recording_url} target="_blank" rel="noopener noreferrer">
                              <ExternalLink className="h-3 w-3" />
                            </a>
                          </Button>
                        ) : (
                          <span className="text-xs text-muted-foreground">—</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {[
          { icon: Phone, title: "1. Request Help", desc: "Engineer taps 'Request AR Assist' from the job card" },
          { icon: Video, title: "2. Live Video + AR", desc: "Mentor views camera feed and draws annotations in real-time" },
          { icon: Clock, title: "3. Auto-Documented", desc: "Session recorded and linked to job for compliance" },
        ].map((step, i) => (
          <Card key={i}>
            <CardContent className="py-4 text-center space-y-2">
              <step.icon className="h-6 w-6 text-primary mx-auto" />
              <p className="text-sm font-semibold text-foreground">{step.title}</p>
              <p className="text-xs text-muted-foreground">{step.desc}</p>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default AREngineerSupport;
