"use client";

import {useState} from "react";
import Image from "next/image";
import {useRouter} from "next/navigation";
import {useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {z} from "zod";
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 {Select} from "@/components/ui/select";
import {Textarea} from "@/components/ui/textarea";
import {Car, Calendar, User, CheckCircle2, ChevronRight} from "lucide-react";
import {createBooking} from "./actions";

const datesSchema = z.object({
  pickupAt: z.string().min(1, "Required"),
  dropoffAt: z.string().min(1, "Required"),
  pickupBranchId: z.string().min(1, "Required"),
  dropoffBranchId: z.string().min(1, "Required")
});

const customerSchema = z.object({
  firstName: z.string().min(1, "Required"),
  lastName: z.string().min(1, "Required"),
  phone: z.string().min(5, "Required"),
  licenseNumber: z.string().optional(),
  notes: z.string().optional()
});

type DatesForm = z.infer<typeof datesSchema>;
type CustomerForm = z.infer<typeof customerSchema>;

type BookingWizardProps = {
  vehicle: {
    id: string;
    name: string;
    dailyRate: number;
    depositAmount: number;
    primaryImageUrl: string | null;
    brandName: string;
  };
  branches: Array<{id: string; name: string; city: string}>;
  user: {email: string; firstName: string; lastName: string; phone: string};
};

export function BookingWizard({vehicle, branches, user}: BookingWizardProps) {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [datesData, setDatesData] = useState<DatesForm | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const datesForm = useForm<DatesForm>({resolver: zodResolver(datesSchema)});
  const customerForm = useForm<CustomerForm>({
    resolver: zodResolver(customerSchema),
    defaultValues: {firstName: user.firstName, lastName: user.lastName, phone: user.phone}
  });

  const pickupAt = datesForm.watch("pickupAt");
  const dropoffAt = datesForm.watch("dropoffAt");
  const rentalDays = pickupAt && dropoffAt
    ? Math.max(1, Math.ceil((new Date(dropoffAt).getTime() - new Date(pickupAt).getTime()) / (1000 * 60 * 60 * 24)))
    : 0;
  const subtotal = rentalDays * vehicle.dailyRate;
  const total = subtotal + vehicle.depositAmount;

  function handleDatesSubmit(data: DatesForm) {
    setDatesData(data);
    setStep(2);
  }

  async function handleCustomerSubmit(data: CustomerForm) {
    if (!datesData) return;
    setIsSubmitting(true);
    setError(null);
    try {
      const result = await createBooking({
        vehicleId: vehicle.id,
        ...datesData,
        ...data
      });
      if (result.success) {
        router.push(`/bookings/success?bookingNumber=${result.bookingNumber}`);
      } else {
        setError(result.error);
      }
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  }

  const steps = [
    {icon: Calendar, label: "Dates & Branch"},
    {icon: User, label: "Your Details"},
    {icon: CheckCircle2, label: "Confirm"}
  ];

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold text-slate-900">New Booking</h1>

      {/* Step Indicator */}
      <div className="mb-8 flex items-center gap-2">
        {steps.map(({icon: Icon, label}, idx) => {
          const s = idx + 1;
          return (
            <div key={s} className="flex items-center gap-2">
              <div className={`flex h-9 w-9 items-center justify-center rounded-full text-sm font-semibold transition ${step >= s ? "bg-blue-600 text-white" : "bg-slate-100 text-slate-400"}`}>
                <Icon className="h-4 w-4" />
              </div>
              <span className={`hidden text-sm sm:block ${step >= s ? "font-medium text-slate-900" : "text-slate-400"}`}>{label}</span>
              {idx < steps.length - 1 && <ChevronRight className="h-4 w-4 text-slate-300" />}
            </div>
          );
        })}
      </div>

      {/* Vehicle Summary */}
      <Card className="mb-6 border-blue-100 bg-blue-50">
        <CardContent className="flex items-center gap-4 p-4">
          <div className="relative h-16 w-24 overflow-hidden rounded-lg bg-slate-200 shrink-0">
            {vehicle.primaryImageUrl ? (
              <Image src={vehicle.primaryImageUrl} alt={vehicle.name} fill className="object-cover" unoptimized />
            ) : (
              <div className="flex h-full items-center justify-center"><Car className="h-8 w-8 text-slate-400" /></div>
            )}
          </div>
          <div>
            <p className="text-xs font-medium text-blue-600">{vehicle.brandName}</p>
            <p className="font-semibold text-slate-900">{vehicle.name}</p>
            <p className="text-sm text-slate-600">${vehicle.dailyRate}/day</p>
          </div>
        </CardContent>
      </Card>

      {/* Step 1: Dates */}
      {step === 1 && (
        <form onSubmit={datesForm.handleSubmit(handleDatesSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>Rental Dates</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <Label htmlFor="pickupAt">Pickup Date *</Label>
                  <Input
                    id="pickupAt"
                    type="date"
                    min={new Date().toISOString().split("T")[0]}
                    {...datesForm.register("pickupAt")}
                    className="mt-1"
                  />
                  {datesForm.formState.errors.pickupAt && <p className="mt-1 text-xs text-red-500">{datesForm.formState.errors.pickupAt.message}</p>}
                </div>
                <div>
                  <Label htmlFor="dropoffAt">Return Date *</Label>
                  <Input
                    id="dropoffAt"
                    type="date"
                    min={pickupAt || new Date().toISOString().split("T")[0]}
                    {...datesForm.register("dropoffAt")}
                    className="mt-1"
                  />
                  {datesForm.formState.errors.dropoffAt && <p className="mt-1 text-xs text-red-500">{datesForm.formState.errors.dropoffAt.message}</p>}
                </div>
              </div>
              {rentalDays > 0 && (
                <div className="rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-800">
                  {rentalDays} day{rentalDays !== 1 ? "s" : ""} rental — Subtotal: ${subtotal.toFixed(2)}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader><CardTitle>Pickup & Return Branch</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="pickupBranchId">Pickup Branch *</Label>
                <Select id="pickupBranchId" {...datesForm.register("pickupBranchId")} className="mt-1">
                  <option value="">Select branch...</option>
                  {branches.map((b) => (
                    <option key={b.id} value={b.id}>{b.name}{b.city ? ` — ${b.city}` : ""}</option>
                  ))}
                </Select>
                {datesForm.formState.errors.pickupBranchId && <p className="mt-1 text-xs text-red-500">{datesForm.formState.errors.pickupBranchId.message}</p>}
              </div>
              <div>
                <Label htmlFor="dropoffBranchId">Return Branch *</Label>
                <Select id="dropoffBranchId" {...datesForm.register("dropoffBranchId")} className="mt-1">
                  <option value="">Select branch...</option>
                  {branches.map((b) => (
                    <option key={b.id} value={b.id}>{b.name}{b.city ? ` — ${b.city}` : ""}</option>
                  ))}
                </Select>
                {datesForm.formState.errors.dropoffBranchId && <p className="mt-1 text-xs text-red-500">{datesForm.formState.errors.dropoffBranchId.message}</p>}
              </div>
            </CardContent>
          </Card>

          <Button type="submit" className="w-full" size="lg">
            Continue to Details <ChevronRight className="ml-1 h-4 w-4" />
          </Button>
        </form>
      )}

      {/* Step 2: Customer Details */}
      {step === 2 && (
        <form onSubmit={customerForm.handleSubmit(handleCustomerSubmit)} className="space-y-6">
          <Card>
            <CardHeader><CardTitle>Your Details</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <Label htmlFor="firstName">First Name *</Label>
                  <Input id="firstName" {...customerForm.register("firstName")} className="mt-1" />
                  {customerForm.formState.errors.firstName && <p className="mt-1 text-xs text-red-500">{customerForm.formState.errors.firstName.message}</p>}
                </div>
                <div>
                  <Label htmlFor="lastName">Last Name *</Label>
                  <Input id="lastName" {...customerForm.register("lastName")} className="mt-1" />
                  {customerForm.formState.errors.lastName && <p className="mt-1 text-xs text-red-500">{customerForm.formState.errors.lastName.message}</p>}
                </div>
              </div>
              <div>
                <Label>Email</Label>
                <Input value={user.email} disabled className="mt-1 bg-slate-50" />
              </div>
              <div>
                <Label htmlFor="phone">Phone *</Label>
                <Input id="phone" {...customerForm.register("phone")} className="mt-1" />
                {customerForm.formState.errors.phone && <p className="mt-1 text-xs text-red-500">{customerForm.formState.errors.phone.message}</p>}
              </div>
              <div>
                <Label htmlFor="licenseNumber">Driver License Number (optional)</Label>
                <Input id="licenseNumber" {...customerForm.register("licenseNumber")} className="mt-1" />
              </div>
              <div>
                <Label htmlFor="notes">Special Notes (optional)</Label>
                <Textarea id="notes" {...customerForm.register("notes")} className="mt-1" rows={3} />
              </div>
            </CardContent>
          </Card>

          {/* Booking Summary */}
          {datesData && rentalDays > 0 && (
            <Card className="border-slate-200 bg-slate-50">
              <CardHeader><CardTitle>Booking Summary</CardTitle></CardHeader>
              <CardContent className="space-y-3 text-sm">
                <div className="flex justify-between"><span className="text-slate-600">Daily Rate</span><span className="font-medium">${vehicle.dailyRate}/day</span></div>
                <div className="flex justify-between"><span className="text-slate-600">Rental Days</span><span className="font-medium">{rentalDays} days</span></div>
                <div className="flex justify-between"><span className="text-slate-600">Subtotal</span><span className="font-medium">${subtotal.toFixed(2)}</span></div>
                <div className="flex justify-between"><span className="text-slate-600">Security Deposit</span><span className="font-medium">${vehicle.depositAmount.toFixed(2)}</span></div>
                <hr className="border-slate-200" />
                <div className="flex justify-between text-base font-bold text-slate-900"><span>Total</span><span>${total.toFixed(2)}</span></div>
              </CardContent>
            </Card>
          )}

          {error && (
            <div className="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700">{error}</div>
          )}

          <div className="flex gap-3">
            <Button type="button" variant="outline" onClick={() => setStep(1)} className="flex-1">
              Back
            </Button>
            <Button type="submit" disabled={isSubmitting} className="flex-1 bg-blue-600 hover:bg-blue-700" size="lg">
              {isSubmitting ? "Processing..." : "Confirm Booking"}
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}
