import { useState, useEffect } from "react";
import { router } from "@inertiajs/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from "sonner";
import { User, Mail, Phone, Save, ArrowLeft, Award, BookOpen, Calendar, MapPin, GraduationCap, ShieldCheck, ClipboardList, Clock, ChevronRight } from "lucide-react";
import { format, differenceInDays } from "date-fns";

const bookingStatusConfig: Record<string, { class: string; label: string }> = {
  pending: { class: "bg-yellow-500/10 text-yellow-600 border-yellow-500/30", label: "Pending" },
  paid: { class: "bg-green-500/10 text-green-600 border-green-500/30", label: "Paid" },
  confirmed: { class: "bg-blue-500/10 text-blue-600 border-blue-500/30", label: "Confirmed" },
  completed: { class: "bg-emerald-500/10 text-emerald-600 border-emerald-500/30", label: "Completed" },
  cancelled: { class: "bg-red-500/10 text-red-600 border-red-500/30", label: "Cancelled" },
  refunded: { class: "bg-purple-500/10 text-purple-600 border-purple-500/30", label: "Refunded" },
};

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

const DelegateProfile = () => {
  const { user } = useAuth();
  const queryClient = useQueryClient();

  const { data: profile, isLoading } = useQuery({
    queryKey: ["delegate-profile", user?.id],
    queryFn: async () => {
      const res = await fetch(`/api/delegate/profile`);
      if (!res.ok) throw new Error("Failed to load profile");
      return await res.json();
    },
    enabled: !!user?.id,
  });

  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);

  const { data: orderDetail, isLoading: orderDetailLoading } = useQuery({
    queryKey: ["delegate-order-detail", selectedOrderId],
    enabled: !!selectedOrderId,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/orders/${selectedOrderId}`);
      if (!res.ok) throw new Error("Failed to load booking details");
      return await res.json();
    },
  });

  // Set form values when profile loads
  useEffect(() => {
    if (profile) {
      setFullName(profile.full_name || "");
      setPhone(profile.phone || "");
    }
  }, [profile]);

  const updateMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch(`/api/delegate/profile`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ full_name: fullName, phone }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || 'Failed to update profile');
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["delegate-profile"] });
      toast.success("Profile updated");
      setIsEditing(false);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const { data: certificates } = useQuery({
    queryKey: ["delegate-certs", user?.email],
    queryFn: async () => {
      const res = await fetch(`/api/delegate/certificates?email=${encodeURIComponent(user!.email!)}`);
      if (!res.ok) throw new Error("Failed to load certificates");
      return await res.json();
    },
    enabled: !!user?.email,
  });

  const { data: enrolments } = useQuery({
    queryKey: ["delegate-enrolments", user?.id],
    queryFn: async () => {
      const res = await fetch(`/api/delegate/enrolments`);
      if (!res.ok) throw new Error("Failed to load enrolments");
      return await res.json();
    },
    enabled: !!user?.id,
  });

  const { data: orders } = useQuery({
    queryKey: ["delegate-orders", user?.email],
    queryFn: async () => {
      const res = await fetch(`/api/delegate/orders?email=${encodeURIComponent(user!.email!)}`);
      if (!res.ok) throw new Error("Failed to load bookings");
      return await res.json();
    },
    enabled: !!user?.email,
  });

  const today = new Date();
  const upcomingBookings = (orders || []).filter((o: any) => {
    if (!o.start_date) return false;
    const d = differenceInDays(new Date(o.start_date + "T00:00:00"), today);
    return d >= 0 && o.status !== "cancelled" && o.status !== "refunded";
  });
  const pastBookings = (orders || []).filter((o: any) => {
    if (!o.start_date) return false;
    const d = differenceInDays(new Date(o.start_date + "T00:00:00"), today);
    return d < 0 || o.status === "completed" || o.status === "cancelled" || o.status === "refunded";
  });

  if (!user) {
    router.visit("/auth");
    return null;
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />
      <div className="pt-20 pb-16">
        <div className="container mx-auto px-4 max-w-4xl">
          <Button variant="ghost" size="sm" className="mb-4" onClick={() => window.history.back()}>
            <ArrowLeft className="h-4 w-4 mr-1" /> Back
          </Button>

          <h1 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-2">
            <User className="h-6 w-6 text-primary" /> My Profile
          </h1>

          <div className="grid md:grid-cols-2 gap-6">
            {/* Profile info */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Personal Information</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label>Full Name</Label>
                  {isEditing ? (
                    <Input
                      value={fullName}
                      onChange={(e) => setFullName(e.target.value)}
                      placeholder="Your full name"
                    />
                  ) : (
                    <p className="text-sm text-foreground mt-1">{profile?.full_name || "Not set"}</p>
                  )}
                </div>
                <div>
                  <Label className="flex items-center gap-1"><Mail className="h-3 w-3" /> Email</Label>
                  <p className="text-sm text-muted-foreground mt-1">{user.email}</p>
                </div>
                <div>
                  <Label className="flex items-center gap-1"><Phone className="h-3 w-3" /> Phone</Label>
                  {isEditing ? (
                    <Input
                      type="tel"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      placeholder="Optional"
                    />
                  ) : (
                    <p className="text-sm text-foreground mt-1">{profile?.phone || "Not set"}</p>
                  )}
                </div>

                {isEditing ? (
                  <div className="flex gap-2">
                    <Button variant="hero" size="sm" onClick={() => updateMutation.mutate()} disabled={updateMutation.isPending}>
                      <Save className="h-4 w-4 mr-1" /> Save
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => setIsEditing(false)}>Cancel</Button>
                  </div>
                ) : (
                  <Button variant="outline" size="sm" onClick={() => { setFullName(profile?.full_name || ""); setPhone(profile?.phone || ""); setIsEditing(true); }}>
                    Edit Profile
                  </Button>
                )}
              </CardContent>
            </Card>

            {/* Stats */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Overview</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-4">
                  <div className="text-center p-3 bg-muted/50 rounded-lg">
                    <Calendar className="h-5 w-5 text-primary mx-auto mb-1" />
                    <p className="text-2xl font-bold text-foreground">{upcomingBookings.length}</p>
                    <p className="text-xs text-muted-foreground">Upcoming Bookings</p>
                  </div>
                  <div className="text-center p-3 bg-muted/50 rounded-lg">
                    <Award className="h-5 w-5 text-primary mx-auto mb-1" />
                    <p className="text-2xl font-bold text-foreground">{certificates?.length || 0}</p>
                    <p className="text-xs text-muted-foreground">Certificates</p>
                  </div>
                  <div className="text-center p-3 bg-muted/50 rounded-lg">
                    <BookOpen className="h-5 w-5 text-primary mx-auto mb-1" />
                    <p className="text-2xl font-bold text-foreground">{enrolments?.length || 0}</p>
                    <p className="text-xs text-muted-foreground">E-Learning Courses</p>
                  </div>
                  <div className="text-center p-3 bg-muted/50 rounded-lg">
                    <p className="text-2xl font-bold text-foreground">
                      {certificates?.filter((c: any) => c.expires_at && differenceInDays(new Date(c.expires_at), new Date()) <= 30 && differenceInDays(new Date(c.expires_at), new Date()) >= 0).length || 0}
                    </p>
                    <p className="text-xs text-muted-foreground">Expiring in 30 days</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* My Bookings */}
          {(upcomingBookings.length > 0 || pastBookings.length > 0) && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-sm font-medium flex items-center gap-2">
                  <GraduationCap className="h-4 w-4" /> My Bookings
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                {upcomingBookings.length > 0 && (
                  <div>
                    <h3 className="text-xs font-semibold text-muted-foreground mb-2 uppercase tracking-wide">
                      Upcoming ({upcomingBookings.length})
                    </h3>
                    <div className="space-y-3">
                      {upcomingBookings.map((order: any) => {
                        const startDate = new Date(order.start_date + "T00:00:00");
                        const daysUntil = differenceInDays(startDate, today);
                        return (
                          <button
                            key={order.id}
                            type="button"
                            onClick={() => setSelectedOrderId(order.id)}
                            className="w-full text-left p-3 bg-muted/30 rounded-lg border border-border/50 hover:bg-muted/50 hover:border-border transition-colors"
                          >
                            <div className="flex items-start justify-between gap-3">
                              <div className="flex-1 min-w-0">
                                <p className="text-sm font-medium text-foreground flex items-center gap-1">
                                  {order.courses?.title || order.course?.title || "Course"}
                                  <ChevronRight className="h-3 w-3 text-muted-foreground" />
                                </p>
                                <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-muted-foreground">
                                  <span className="flex items-center gap-1">
                                    <Calendar className="h-3 w-3" />
                                    {format(startDate, "EEE d MMM yyyy")}
                                  </span>
                                  {order.venue?.name && (
                                    <span className="flex items-center gap-1">
                                      <MapPin className="h-3 w-3" />
                                      {order.venue.name}
                                    </span>
                                  )}
                                  {order.num_delegates > 1 && (
                                    <span>{order.num_delegates} delegates</span>
                                  )}
                                </div>
                              </div>
                              <div className="flex flex-col items-end gap-1 shrink-0">
                                <Badge variant="outline" className={bookingStatusConfig[order.status]?.class || ""}>
                                  {bookingStatusConfig[order.status]?.label || order.status}
                                </Badge>
                                <span className="text-[10px] text-muted-foreground">
                                  {daysUntil === 0 ? "Today" : daysUntil === 1 ? "Tomorrow" : `in ${daysUntil} days`}
                                </span>
                              </div>
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                )}

                {pastBookings.length > 0 && (
                  <div>
                    <h3 className="text-xs font-semibold text-muted-foreground mb-2 uppercase tracking-wide">
                      Past ({pastBookings.length})
                    </h3>
                    <div className="space-y-3">
                      {pastBookings.slice(0, 5).map((order: any) => {
                        const startDate = new Date(order.start_date + "T00:00:00");
                        return (
                          <button
                            key={order.id}
                            type="button"
                            onClick={() => setSelectedOrderId(order.id)}
                            className="w-full text-left p-3 bg-muted/20 rounded-lg border border-border/30 hover:bg-muted/40 hover:border-border/60 transition-colors"
                          >
                            <div className="flex items-start justify-between gap-3">
                              <div className="flex-1 min-w-0">
                                <p className="text-sm font-medium text-foreground flex items-center gap-1">
                                  {order.courses?.title || order.course?.title || "Course"}
                                  <ChevronRight className="h-3 w-3 text-muted-foreground" />
                                </p>
                                <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-muted-foreground">
                                  <span className="flex items-center gap-1">
                                    <Calendar className="h-3 w-3" />
                                    {format(startDate, "d MMM yyyy")}
                                  </span>
                                  {order.venue?.name && (
                                    <span className="flex items-center gap-1">
                                      <MapPin className="h-3 w-3" />
                                      {order.venue.name}
                                    </span>
                                  )}
                                </div>
                              </div>
                              <Badge variant="outline" className={bookingStatusConfig[order.status]?.class || ""}>
                                {bookingStatusConfig[order.status]?.label || order.status}
                              </Badge>
                            </div>
                          </button>
                        );
                      })}
                      {pastBookings.length > 5 && (
                        <p className="text-xs text-muted-foreground text-center pt-1">
                          + {pastBookings.length - 5} more
                        </p>
                      )}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Recent Certificates */}
          {certificates && certificates.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-sm font-medium">Recent Certificates</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {certificates.slice(0, 5).map((cert: any) => {
                    const daysLeft = cert.expires_at ? differenceInDays(new Date(cert.expires_at), new Date()) : null;
                    return (
                      <div key={cert.id} className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
                        <div>
                          <p className="text-sm font-medium text-foreground">{cert.courses?.title || "Certificate"}</p>
                          <p className="text-xs text-muted-foreground">
                            Issued: {format(new Date(cert.issued_at), "dd MMM yyyy")}
                            {cert.certificate_number && ` · #${cert.certificate_number}`}
                          </p>
                        </div>
                        <div className="flex items-center gap-2">
                          {daysLeft !== null && (
                            <Badge variant={daysLeft < 0 ? "destructive" : daysLeft <= 30 ? "outline" : "default"}>
                              {daysLeft < 0 ? "Expired" : `${daysLeft}d left`}
                            </Badge>
                          )}
                          {cert.certificate_url && (
                            <a href={cert.certificate_url} target="_blank" rel="noopener noreferrer">
                              <Button variant="outline" size="sm">Download</Button>
                            </a>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </CardContent>
            </Card>
          )}

          {/* E-Learning Progress */}
          {enrolments && enrolments.length > 0 && (
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-sm font-medium">E-Learning Progress</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {enrolments.map((e: any) => (
                    <div key={e.id} className="flex items-center justify-between p-3 bg-muted/30 rounded-lg">
                      <div className="flex-1 min-w-0 mr-4">
                        <p className="text-sm font-medium text-foreground">{e.courses?.title || "Course"}</p>
                        <div className="flex items-center gap-2 mt-1">
                          <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                            <div className="h-full bg-primary rounded-full transition-all" style={{ width: `${e.progress_percent}%` }} />
                          </div>
                          <span className="text-xs text-muted-foreground">{e.progress_percent}%</span>
                        </div>
                      </div>
                      <Badge variant={e.status === "completed" ? "default" : "outline"}>
                        {e.status === "completed" ? "Complete" : e.status === "in_progress" ? "In Progress" : "Not Started"}
                      </Badge>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>

      {/* Booking detail dialog */}
      <Dialog open={!!selectedOrderId} onOpenChange={(open) => { if (!open) setSelectedOrderId(null); }}>
        <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <GraduationCap className="h-5 w-5 text-primary" />
              Booking Details
            </DialogTitle>
          </DialogHeader>

          {orderDetailLoading && (
            <p className="text-sm text-muted-foreground py-8 text-center">Loading…</p>
          )}

          {!orderDetailLoading && orderDetail && (
            <div className="space-y-5">
              {/* Header: title + status */}
              <div className="flex items-start justify-between gap-3">
                <div>
                  <h3 className="text-lg font-semibold text-foreground">{orderDetail.courses?.title}</h3>
                  <p className="text-xs text-muted-foreground font-mono mt-0.5">
                    Order #{orderDetail.id?.slice(0, 8)}
                  </p>
                </div>
                <Badge variant="outline" className={bookingStatusConfig[orderDetail.status]?.class || ""}>
                  {bookingStatusConfig[orderDetail.status]?.label || orderDetail.status}
                </Badge>
              </div>

              {/* Date / duration / level */}
              <div className="bg-muted/50 rounded-lg p-4 grid grid-cols-2 gap-3 text-sm">
                <div>
                  <span className="text-muted-foreground text-xs flex items-center gap-1">
                    <Calendar className="h-3 w-3" /> Course Date
                  </span>
                  <p className="font-medium mt-0.5">
                    {orderDetail.start_date && format(new Date(orderDetail.start_date + "T00:00:00"), "EEE, d MMM yyyy")}
                  </p>
                </div>
                {orderDetail.courses?.days && (
                  <div>
                    <span className="text-muted-foreground text-xs flex items-center gap-1">
                      <Clock className="h-3 w-3" /> Duration
                    </span>
                    <p className="font-medium mt-0.5">
                      {orderDetail.courses.days} day{orderDetail.courses.days > 1 ? "s" : ""}
                    </p>
                  </div>
                )}
                {orderDetail.courses?.level && (
                  <div>
                    <span className="text-muted-foreground text-xs">Level</span>
                    <p className="font-medium mt-0.5">{orderDetail.courses.level}</p>
                  </div>
                )}
                {orderDetail.num_delegates && (
                  <div>
                    <span className="text-muted-foreground text-xs">Delegates</span>
                    <p className="font-medium mt-0.5">{orderDetail.num_delegates}</p>
                  </div>
                )}
              </div>

              {/* Instructor */}
              {orderDetail.trainer && (
                <div className="bg-secondary/30 rounded-lg p-4">
                  <h4 className="text-sm font-semibold flex items-center gap-2 mb-1">
                    <User className="h-4 w-4" /> Instructor
                  </h4>
                  <p className="text-sm">{orderDetail.trainer.first_name} {orderDetail.trainer.last_name}</p>
                </div>
              )}

              {/* Venue */}
              {orderDetail.venue && (
                <div className="bg-secondary/30 rounded-lg p-4">
                  <h4 className="text-sm font-semibold flex items-center gap-2 mb-1">
                    <MapPin className="h-4 w-4" /> Venue
                  </h4>
                  <p className="text-sm font-medium">{orderDetail.venue.name}</p>
                  {(orderDetail.venue.address || orderDetail.venue.city || orderDetail.venue.postcode) && (
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {[orderDetail.venue.address, orderDetail.venue.city, orderDetail.venue.postcode].filter(Boolean).join(", ")}
                    </p>
                  )}
                  {orderDetail.courses?.location_details && (
                    <div
                      className="prose prose-sm max-w-none text-muted-foreground mt-2 [&_a]:text-primary [&_a]:underline [&_h3]:text-foreground [&_h3]:font-semibold [&_h3]:text-sm [&_h3]:mt-2 [&_h3]:mb-1 [&_strong]:text-foreground"
                      dangerouslySetInnerHTML={{ __html: orderDetail.courses.location_details }}
                    />
                  )}
                </div>
              )}

              {/* PPE Requirements */}
              {orderDetail.courses?.ppe_requirements && (() => {
                const raw: string = orderDetail.courses.ppe_requirements;
                let items: string[] = [];
                try {
                  const parsed = JSON.parse(raw);
                  if (Array.isArray(parsed)) items = parsed.filter(Boolean);
                } catch {
                  items = raw.split(/\n|,\s*/).map((s) => s.trim()).filter(Boolean);
                }
                return (
                  <div className="bg-amber-500/5 border border-amber-500/20 rounded-lg p-4">
                    <h4 className="text-sm font-semibold flex items-center gap-2 mb-2 text-amber-700">
                      <ShieldCheck className="h-4 w-4" /> PPE Requirements
                    </h4>
                    {items.length > 1 ? (
                      <ul className="list-disc list-inside space-y-1 text-sm">
                        {items.map((item, i) => <li key={i}>{item}</li>)}
                      </ul>
                    ) : (
                      <p className="text-sm whitespace-pre-line">{items[0] || raw}</p>
                    )}
                  </div>
                );
              })()}

              {/* Course content */}
              {orderDetail.courses?.course_content && (() => {
                const raw: string = orderDetail.courses.course_content;
                let modules: string[] = [];
                try {
                  const parsed = JSON.parse(raw);
                  if (Array.isArray(parsed)) modules = parsed.filter((s: unknown) => typeof s === "string" && s.trim() !== "") as string[];
                } catch {
                  modules = [raw].filter((s) => s.trim() !== "");
                }
                if (modules.length === 0) return null;
                return (
                  <div>
                    <h4 className="text-sm font-semibold flex items-center gap-2 mb-2">
                      <ClipboardList className="h-4 w-4" /> Course Content
                    </h4>
                    {modules.length > 1 ? (
                      <ul className="list-disc list-inside space-y-1 text-sm text-muted-foreground">
                        {modules.map((m, i) => <li key={i}>{m}</li>)}
                      </ul>
                    ) : (
                      <p className="text-sm text-muted-foreground whitespace-pre-line">{modules[0]}</p>
                    )}
                  </div>
                );
              })()}

              {/* Certification */}
              {orderDetail.courses?.certification && (
                <div>
                  <h4 className="text-sm font-semibold flex items-center gap-2 mb-1">
                    <Award className="h-4 w-4" /> Certification
                  </h4>
                  <p className="text-sm text-muted-foreground whitespace-pre-line">{orderDetail.courses.certification}</p>
                </div>
              )}

              {/* Facilities */}
              {orderDetail.courses?.facilities && (
                <div>
                  <h4 className="text-sm font-semibold mb-1">Facilities</h4>
                  <p className="text-sm text-muted-foreground whitespace-pre-line">{orderDetail.courses.facilities}</p>
                </div>
              )}

              {orderDetail.courses?.slug && (
                <Button variant="outline" size="sm" className="w-full" onClick={() => router.visit(`/course/${orderDetail.courses.slug}`)}>
                  View course page
                </Button>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      <Footer />
    </div>
  );
};

export default DelegateProfile;
