import { useState } from "react";
import { router } from "@inertiajs/react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { FormTD07 } from "@/components/onboarding/FormTD07";
import { FormTD29 } from "@/components/onboarding/FormTD29";
import { CheckCircle2, FileText } from "lucide-react";
import { toast } from "sonner";

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

type FormStep = 0 | 1 | 2;

const STEPS = [
  { key: "TD-07", label: "Candidate Induction" },
  { key: "TD-29", label: "Health & Safety" },
];

const OnboardingForms = () => {
  const { user } = useAuth();
  const searchParams = new URLSearchParams(window.location.search);
  const orderId = searchParams.get("order_id");

  const [currentStep, setCurrentStep] = useState<FormStep>(0);
  const [formData, setFormData] = useState<Record<string, any>>({});

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

  const { data: delegate } = useQuery({
    queryKey: ["onboarding-delegate", orderId, user?.email],
    enabled: !!orderId && !!user?.email,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/booking-delegates?order_id=${orderId}&email=${encodeURIComponent(user!.email!)}`);
      if (!res.ok) return null;
      return await res.json();
    },
  });

  // Build the candidate name defensively. The API may return null (no email
  // match), a partial row (one or both name columns null), or a full row.
  // Fall back through: full booking-delegate name → user's full_name → email.
  const delegateName = (() => {
    const first = (delegate?.first_name ?? '').toString().trim();
    const last = (delegate?.last_name ?? '').toString().trim();
    const combined = `${first} ${last}`.trim();
    if (combined) return combined;
    const userFullName = ((user as any)?.full_name ?? (user as any)?.name ?? '').toString().trim();
    if (userFullName) return userFullName;
    return user?.email ?? '';
  })();

  const submitMutation = useMutation({
    mutationFn: async (allFormData: Record<string, any>) => {
      const submissions = [
        {
          form_type: "TD-07",
          form_data: allFormData["TD-07"],
          candidate_signature: allFormData["TD-07"]?.candidate_signature,
          assessor_signature: allFormData["TD-07"]?.assessor_signature,
        },
        {
          form_type: "TD-29",
          form_data: allFormData["TD-29"],
          candidate_signature: allFormData["TD-29"]?.candidate_signature,
          assessor_signature: allFormData["TD-29"]?.assessor_signature,
        },
      ];

      for (const sub of submissions) {
        const res = await fetch('/api/delegate/form-submissions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
          body: JSON.stringify({
            delegate_email: user?.email || "",
            order_id: orderId,
            course_id: order?.course_id,
            form_type: sub.form_type,
            form_data: sub.form_data,
            candidate_signature: sub.candidate_signature,
            assessor_signature: sub.assessor_signature,
          }),
        });
        if (!res.ok) {
          const err = await res.json().catch(() => ({}));
          throw new Error(`Failed to save ${sub.form_type}: ${err.message || res.statusText}`);
        }
      }
    },
    onSuccess: () => {
      setCurrentStep(2);
    },
    onError: (err: Error) => {
      toast.error(err.message || "Failed to submit forms. Please try again.");
    },
  });

  const handleTD07Complete = (data: any) => {
    setFormData(p => ({ ...p, "TD-07": data }));
    setCurrentStep(1);
  };

  const td07Data = formData["TD-07"];

  const handleTD29Complete = (data: any) => {
    const allData = { ...formData, "TD-29": data };
    setFormData(allData);
    submitMutation.mutate(allData);
  };

  if (currentStep === 2) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center px-4" style={{ background: "#f8fafc" }}>
        <div className="max-w-md w-full text-center space-y-6">
          <div className="w-20 h-20 rounded-full flex items-center justify-center mx-auto" style={{ background: "#dcfce7" }}>
            <CheckCircle2 className="w-10 h-10" style={{ color: "#16a34a" }} />
          </div>
          <div>
            <h1 className="text-2xl font-bold" style={{ color: "#0f172a" }}>All done!</h1>
            <p className="text-sm mt-2" style={{ color: "#64748b" }}>
              Your induction forms have been submitted successfully. You're ready for training.
            </p>
          </div>
          <button
            className="text-sm font-medium"
            style={{ color: "#f97316" }}
            onClick={() => router.visit(`/delegate-dashboard${orderId ? `?order_id=${orderId}` : ""}`)}
          >
            Return to your dashboard →
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col" style={{ background: "#f8fafc" }}>
      {/* Header */}
      <header className="sticky top-0 z-10" style={{ background: "#ffffff", borderBottom: "1px solid #e2e8f0" }}>
        <div className="max-w-2xl mx-auto px-4 py-4">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: "#f97316" }}>
              <FileText className="w-4 h-4" style={{ color: "#ffffff" }} />
            </div>
            <div>
              <p className="text-sm font-semibold" style={{ color: "#0f172a" }}>On-the-Day Induction</p>
              {order?.courses && (
                <p className="text-xs" style={{ color: "#64748b" }}>{(order.courses as any).title}</p>
              )}
            </div>
          </div>

          {/* Step progress */}
          <div className="flex items-center gap-2">
            {STEPS.map((step, i) => (
              <div key={step.key} className="flex items-center gap-2 flex-1">
                <div className="flex items-center gap-1.5" style={{ opacity: i <= currentStep ? 1 : 0.4 }}>
                  <div
                    className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold shrink-0"
                    style={{
                      background: i < currentStep ? "#16a34a" : i === currentStep ? "#f97316" : "#e2e8f0",
                      color: i < currentStep || i === currentStep ? "#ffffff" : "#64748b",
                    }}
                  >
                    {i < currentStep ? "✓" : i + 1}
                  </div>
                  <span
                    className="text-xs hidden sm:block"
                    style={{
                      color: i === currentStep ? "#0f172a" : "#64748b",
                      fontWeight: i === currentStep ? 600 : 400,
                    }}
                  >
                    {step.label}
                  </span>
                </div>
                {i < STEPS.length - 1 && (
                  <div
                    className="h-0.5 flex-1"
                    style={{ background: i < currentStep ? "#16a34a" : "#e2e8f0" }}
                  />
                )}
              </div>
            ))}
          </div>
        </div>
      </header>

      {/* Form content */}
      <div className="flex-1 max-w-2xl w-full mx-auto px-4 py-6">
        <div className="rounded-2xl p-6" style={{ background: "#ffffff", border: "1px solid #e2e8f0" }}>
          {currentStep === 0 && (
            <FormTD07 delegateName={delegateName} onComplete={handleTD07Complete} />
          )}
          {currentStep === 1 && (
            <FormTD29
              delegateName={delegateName}
              prefillInstructorName={td07Data?.assessor_name}
              prefillInstructorReg={td07Data?.assessor_number}
              onComplete={handleTD29Complete}
            />
          )}
        </div>

        {submitMutation.isPending && (
          <div className="fixed inset-0 flex items-center justify-center z-50" style={{ background: "rgba(248,250,252,0.85)" }}>
            <div className="text-center space-y-3">
              <div className="w-12 h-12 rounded-full border-4 border-t-transparent animate-spin mx-auto" style={{ borderColor: "#f97316", borderTopColor: "transparent" }} />
              <p className="text-sm font-medium" style={{ color: "#0f172a" }}>Saving your forms...</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OnboardingForms;
