import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { CheckCircle2, XCircle, Clock, Loader2, SendHorizonal } from "lucide-react";
import { format } from "date-fns";
import { toast } from "sonner";
import { useState } from "react";

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

interface CompanyBookingRequestsTabProps {
  companyId: string;
}

export const CompanyBookingRequestsTab = ({ companyId }: CompanyBookingRequestsTabProps) => {
  const queryClient = useQueryClient();

  const { data: requests, isLoading } = useQuery({
    queryKey: ["booking-requests", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/admin/companies/${companyId}/booking-requests`);
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: company } = useQuery({
    queryKey: ["company-credit", companyId],
    queryFn: async () => {
      const res = await fetch(`/api/admin/companies/${companyId}/credit`);
      if (!res.ok) return null;
      return res.json();
    },
  });

  const [notes, setNotes] = useState<Record<string, string>>({});

  const approveMutation = useMutation({
    mutationFn: async (requestId: string) => {
      const res = await fetch(`/api/admin/booking-requests/${requestId}/approve`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ company_id: companyId, manager_notes: notes[requestId] || null }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: 'Failed' }));
        throw new Error(err.error || 'Failed to approve');
      }
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["booking-requests"] });
      queryClient.invalidateQueries({ queryKey: ["company-credit"] });
      toast.success("Booking approved and order created");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const rejectMutation = useMutation({
    mutationFn: async (requestId: string) => {
      const res = await fetch(`/api/admin/booking-requests/${requestId}/reject`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ manager_notes: notes[requestId] || null }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: 'Failed' }));
        throw new Error(err.error || 'Failed to reject');
      }
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["booking-requests"] });
      toast.success("Request rejected");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const pending = requests?.filter((r: any) => r.status === "pending") || [];
  const resolved = requests?.filter((r: any) => r.status !== "pending") || [];

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {company && (
        <div className="bg-muted/50 rounded-lg p-4 flex items-center justify-between">
          <span className="text-sm text-muted-foreground">Available company credit</span>
          <span className="text-lg font-bold text-foreground">£{(company.credit_available_cents / 100).toFixed(2)}</span>
        </div>
      )}

      <div>
        <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
          <Clock className="w-4 h-4 text-amber-500" /> Pending Requests ({pending.length})
        </h3>
        {!pending.length ? (
          <Card>
            <CardContent className="py-8 text-center text-muted-foreground text-sm">
              <SendHorizonal className="w-8 h-8 mx-auto mb-2 opacity-30" />
              No pending booking requests
            </CardContent>
          </Card>
        ) : (
          <div className="space-y-3">
            {pending.map((req: any) => (
              <Card key={req.id} className="border-amber-200 dark:border-amber-800">
                <CardContent className="py-4 space-y-3">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="text-sm font-semibold text-foreground">{req.courses?.title || "Course"}</p>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        Requested by <span className="font-medium">{req.delegate_name}</span> ({req.delegate_email})
                      </p>
                      <div className="flex gap-3 mt-1 text-xs text-muted-foreground">
                        <span>Date: {format(new Date(req.start_date), "EEE d MMM yyyy")}</span>
                        {req.venues && <span>Location: {req.venues.name}</span>}
                        {req.courses?.price_cents && (
                          <span className="font-medium text-foreground">£{(req.courses.price_cents / 100).toFixed(2)}</span>
                        )}
                      </div>
                    </div>
                    <Badge variant="outline" className="text-amber-600 border-amber-300 text-[10px]">
                      Pending
                    </Badge>
                  </div>

                  <Textarea
                    placeholder="Optional note to delegate..."
                    value={notes[req.id] || ""}
                    onChange={(e) => setNotes(prev => ({ ...prev, [req.id]: e.target.value }))}
                    className="h-16 text-xs"
                  />

                  <div className="flex gap-2">
                    <Button
                      size="sm"
                      className="flex-1"
                      onClick={() => approveMutation.mutate(req.id)}
                      disabled={approveMutation.isPending}
                    >
                      <CheckCircle2 className="w-3.5 h-3.5 mr-1" /> Approve & Book
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="flex-1 text-destructive border-destructive/30 hover:bg-destructive/5"
                      onClick={() => rejectMutation.mutate(req.id)}
                      disabled={rejectMutation.isPending}
                    >
                      <XCircle className="w-3.5 h-3.5 mr-1" /> Reject
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {resolved.length > 0 && (
        <div>
          <h3 className="text-sm font-semibold text-foreground mb-3">Previous Requests</h3>
          <div className="space-y-2">
            {resolved.map((req: any) => (
              <Card key={req.id} className="opacity-70">
                <CardContent className="py-3 flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-foreground">{req.courses?.title}</p>
                    <p className="text-xs text-muted-foreground">
                      {req.delegate_name} · {format(new Date(req.start_date), "d MMM yyyy")}
                      {req.manager_notes && <span className="italic"> — {req.manager_notes}</span>}
                    </p>
                  </div>
                  <Badge variant={req.status === "approved" ? "default" : "destructive"} className="text-[10px] capitalize">
                    {req.status}
                  </Badge>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};
