import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { router } from "@inertiajs/react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
  Plus, Trash2, CalendarIcon, Users, ShoppingCart, X,
} from "lucide-react";
import { format } from "date-fns";
import { toast } from "sonner";

const useCart = () => ({ items: [], addItem: (_item: any) => {}, removeItem: () => {}, clearCart: () => {}, total: 0 });

interface CartDelegate {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
}

interface BulkLineItem {
  id: string;
  courseId: string;
  startDate: Date | undefined;
  venueId: string | null;
  delegates: CartDelegate[];
}

const emptyDelegate = (): CartDelegate => ({
  first_name: "", last_name: "", email: "", phone: "",
});

const emptyLine = (): BulkLineItem => ({
  id: crypto.randomUUID(),
  courseId: "",
  startDate: undefined,
  venueId: null,
  delegates: [emptyDelegate()],
});

// Stub hook — backend availability not yet wired up; allow all future dates.
const useCourseAvailability = (_courseId: string, _courseDays: number, _courseCategory: string) => ({
  isDateAvailable: (_d: Date) => true,
  isLoading: false,
});

/* Sub-component for date selection with availability check */
const DatePicker = ({
  courseId,
  courseDays,
  courseCategory,
  selected,
  onSelect,
}: {
  courseId: string;
  courseDays: number;
  courseCategory: string;
  selected: Date | undefined;
  onSelect: (d: Date | undefined) => void;
}) => {
  const { isDateAvailable, isLoading } = useCourseAvailability(courseId, courseDays, courseCategory);
  const [open, setOpen] = useState(false);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button variant="outline" size="sm" className="w-full h-9 text-xs justify-start">
          <CalendarIcon className="w-3 h-3 mr-1.5" />
          {selected ? format(selected, "d MMM yyyy") : "Select date"}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start">
        <Calendar
          mode="single"
          selected={selected}
          onSelect={(d) => { onSelect(d); setOpen(false); }}
          disabled={(d) => isLoading || !isDateAvailable(d)}
          fromDate={new Date()}
        />
      </PopoverContent>
    </Popover>
  );
};

const BulkBookingForm = () => {
  const { user, companyId } = useAuth();
  const { addItem } = useCart();
  const [lines, setLines] = useState<BulkLineItem[]>([emptyLine()]);

  const { data: courses } = useQuery({
    queryKey: ["all-active-courses"],
    queryFn: async () => {
      const res = await fetch(`/api/courses?is_active=1&order=title`);
      if (!res.ok) throw new Error("Failed to load courses");
      const data = await res.json();
      return (data?.data ?? data) as any[];
    },
  });

  const updateLine = (lineId: string, updates: Partial<BulkLineItem>) => {
    setLines(prev => prev.map(l => l.id === lineId ? { ...l, ...updates } : l));
  };

  const addLine = () => {
    if (lines.length >= 10) {
      toast.error("Maximum 10 courses per bulk booking");
      return;
    }
    setLines(prev => [...prev, emptyLine()]);
  };

  const removeLine = (lineId: string) => {
    if (lines.length <= 1) return;
    setLines(prev => prev.filter(l => l.id !== lineId));
  };

  const addDelegateToLine = (lineId: string) => {
    setLines(prev => prev.map(l => {
      if (l.id !== lineId) return l;
      const lineCourse = courses?.find((c: any) => c.id === l.courseId);
      const cap = typeof lineCourse?.capacity === "number" ? lineCourse.capacity : null;
      if (cap !== null && l.delegates.length >= cap) {
        toast.error(`Maximum ${cap} delegate${cap === 1 ? "" : "s"} per course`);
        return l;
      }
      return { ...l, delegates: [...l.delegates, emptyDelegate()] };
    }));
  };

  const removeDelegateFromLine = (lineId: string, idx: number) => {
    setLines(prev => prev.map(l => {
      if (l.id !== lineId || l.delegates.length <= 1) return l;
      return { ...l, delegates: l.delegates.filter((_, i) => i !== idx) };
    }));
  };

  const updateDelegate = (lineId: string, idx: number, field: keyof CartDelegate, value: string) => {
    setLines(prev => prev.map(l => {
      if (l.id !== lineId) return l;
      return {
        ...l,
        delegates: l.delegates.map((d, i) => i === idx ? { ...d, [field]: value } : d),
      };
    }));
  };

  const handleAddAllToCart = () => {
    let valid = true;
    for (const line of lines) {
      if (!line.courseId) {
        toast.error("Please select a course for each line");
        valid = false;
        break;
      }
      if (!line.startDate) {
        toast.error("Please select a date for each course");
        valid = false;
        break;
      }
      for (let i = 0; i < line.delegates.length; i++) {
        if (!line.delegates[i].first_name.trim() || !line.delegates[i].last_name.trim()) {
          toast.error("Please fill in all delegate names");
          valid = false;
          break;
        }
      }
      if (!valid) break;
    }
    if (!valid) return;

    for (const line of lines) {
      const course = courses?.find((c: any) => c.id === line.courseId);
      if (!course || !line.startDate) continue;
      addItem({
        courseId: course.id,
        courseTitle: course.title,
        courseSlug: course.slug,
        priceCents: course.price_cents,
        days: course.days,
        startDate: format(line.startDate, "yyyy-MM-dd"),
        venueId: line.venueId,
        numDelegates: line.delegates.length,
        delegates: line.delegates,
      });
    }

    toast.success(`${lines.length} course${lines.length > 1 ? "s" : ""} added to cart`);
    router.visit("/cart");
  };

  const totalCents = lines.reduce((sum, l) => {
    const course = courses?.find((c: any) => c.id === l.courseId);
    return sum + (course?.price_cents || 0) * l.delegates.length;
  }, 0);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-foreground">Bulk Course Booking</h2>
          <p className="text-sm text-muted-foreground">Select multiple courses, dates, and assign delegates for each</p>
        </div>
        <Badge variant="secondary" className="text-xs">
          {lines.length} course{lines.length > 1 ? "s" : ""}
        </Badge>
      </div>

      <div className="space-y-4">
        {lines.map((line, lineIdx) => {
          const selectedCourse = courses?.find((c: any) => c.id === line.courseId);

          return (
            <Card key={line.id}>
              <CardContent className="p-4 space-y-3">
                <div className="flex items-center justify-between">
                  <p className="text-sm font-semibold text-foreground">Course {lineIdx + 1}</p>
                  {lines.length > 1 && (
                    <Button
                      variant="ghost" size="sm"
                      className="h-7 w-7 p-0 text-muted-foreground hover:text-destructive"
                      onClick={() => removeLine(line.id)}
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  )}
                </div>

                {/* Course selection */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div>
                    <Label className="text-xs">Course *</Label>
                    <Select
                      value={line.courseId}
                      onValueChange={v => updateLine(line.id, { courseId: v, startDate: undefined, venueId: null })}
                    >
                      <SelectTrigger className="h-9 text-xs">
                        <SelectValue placeholder="Select a course" />
                      </SelectTrigger>
                      <SelectContent>
                        {courses?.map((c: any) => (
                          <SelectItem key={c.id} value={c.id} className="text-xs">
                            {c.title} — £{(c.price_cents / 100).toFixed(2)}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label className="text-xs">Start Date *</Label>
                    {selectedCourse ? (
                      <DatePicker
                        courseId={selectedCourse.id}
                        courseDays={selectedCourse.days}
                        courseCategory={selectedCourse.category}
                        selected={line.startDate}
                        onSelect={d => updateLine(line.id, { startDate: d })}
                      />
                    ) : (
                      <Button variant="outline" size="sm" className="w-full h-9 text-xs" disabled>
                        Select a course first
                      </Button>
                    )}
                  </div>
                </div>

                {/* Delegates */}
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label className="text-xs font-medium flex items-center gap-1">
                      <Users className="w-3 h-3" /> Delegates ({line.delegates.length})
                    </Label>
                    {(typeof selectedCourse?.capacity !== "number" || line.delegates.length < selectedCourse.capacity) && (
                      <Button
                        variant="ghost" size="sm"
                        className="h-6 text-[10px] text-primary"
                        onClick={() => addDelegateToLine(line.id)}
                      >
                        <Plus className="w-3 h-3 mr-0.5" /> Add
                      </Button>
                    )}
                  </div>
                  {line.delegates.map((d, di) => (
                    <div key={di} className="flex gap-2 items-end">
                      <div className="flex-1">
                        <Input
                          className="h-8 text-xs"
                          value={d.first_name}
                          onChange={e => updateDelegate(line.id, di, "first_name", e.target.value)}
                          placeholder="First name *"
                        />
                      </div>
                      <div className="flex-1">
                        <Input
                          className="h-8 text-xs"
                          value={d.last_name}
                          onChange={e => updateDelegate(line.id, di, "last_name", e.target.value)}
                          placeholder="Last name *"
                        />
                      </div>
                      <div className="flex-1">
                        <Input
                          className="h-8 text-xs"
                          type="email"
                          value={d.email}
                          onChange={e => updateDelegate(line.id, di, "email", e.target.value)}
                          placeholder="Email"
                        />
                      </div>
                      {line.delegates.length > 1 && (
                        <Button
                          variant="ghost" size="sm"
                          className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive shrink-0"
                          onClick={() => removeDelegateFromLine(line.id, di)}
                        >
                          <Trash2 className="w-3 h-3" />
                        </Button>
                      )}
                    </div>
                  ))}
                </div>

                {/* Line total */}
                {selectedCourse && (
                  <div className="text-right text-xs text-muted-foreground">
                    Subtotal: <span className="font-semibold text-foreground">
                      £{((selectedCourse.price_cents * line.delegates.length) / 100).toFixed(2)}
                    </span>
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })}
      </div>

      <Button variant="outline" className="w-full" onClick={addLine}>
        <Plus className="w-4 h-4 mr-1.5" /> Add Another Course
      </Button>

      {/* Summary footer */}
      <Card>
        <CardContent className="p-4 flex items-center justify-between">
          <div>
            <p className="text-sm font-bold text-foreground">
              Total: £{(totalCents / 100).toFixed(2)}
            </p>
            <p className="text-[10px] text-muted-foreground">
              {lines.length} course{lines.length > 1 ? "s" : ""} ·{" "}
              {lines.reduce((s, l) => s + l.delegates.length, 0)} delegate{lines.reduce((s, l) => s + l.delegates.length, 0) > 1 ? "s" : ""}
            </p>
          </div>
          <Button variant="hero" onClick={handleAddAllToCart}>
            <ShoppingCart className="w-4 h-4 mr-1.5" /> Add All to Cart
          </Button>
        </CardContent>
      </Card>
    </div>
  );
};

export default BulkBookingForm;
