"use client";

import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import {
  User,
  Users,
  ChevronDown,
  ChevronUp,
  Trash2,
  Phone,
  Mail,
  Plus,
  Minus,
  UserPlus,
} from "lucide-react";
import { PACKAGE_DETAIL } from "@/lib/strings";
import type {
  PackageDetailCustomer,
  AgeCategory,
} from "@/features/fixed-packages/types/package-detail.types";
import { getAgeCategory } from "./package-detail-utils";

interface PassengerCardProps {
  customer: PackageDetailCustomer;
  index: number;
  totalCount: number;
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  onUpdate: (
    field: keyof PackageDetailCustomer,
    value: string | number | number[]
  ) => void;
  onRemove: () => void;
}

const AGE_CATEGORY_CONFIG: Record<
  AgeCategory,
  { label: string; variant: "softSuccess" | "softWarning" | "softInfo" }
> = {
  infant: { label: PACKAGE_DETAIL.INFANT_FREE, variant: "softSuccess" },
  child: { label: PACKAGE_DETAIL.CHILD_50, variant: "softWarning" },
  adult: { label: PACKAGE_DETAIL.ADULT_FULL, variant: "softInfo" },
};

function StepperInput({
  value,
  min = 0,
  max = 20,
  onChange,
  id,
}: {
  value: number;
  min?: number;
  max?: number;
  onChange: (value: number) => void;
  id: string;
}) {
  return (
    <div className="flex items-center gap-2">
      <Button
        type="button"
        variant="outline"
        size="sm"
        className="h-9 w-9 rounded-full p-0"
        onClick={() => onChange(Math.max(min, value - 1))}
        disabled={value <= min}
        aria-label={`Decrease ${id}`}
      >
        <Minus className="h-4 w-4" />
      </Button>
      <span
        id={id}
        className="min-w-[2.5rem] text-center text-base font-semibold text-gray-900"
        aria-live="polite"
      >
        {value}
      </span>
      <Button
        type="button"
        variant="outline"
        size="sm"
        className="h-9 w-9 rounded-full p-0"
        onClick={() => onChange(Math.min(max, value + 1))}
        disabled={value >= max}
        aria-label={`Increase ${id}`}
      >
        <Plus className="h-4 w-4" />
      </Button>
    </div>
  );
}

/**
 * Collapsible passenger/party form with contact info, party composition,
 * dynamic children age inputs with category badges.
 */
export function PassengerCard({
  customer,
  index,
  totalCount,
  isOpen,
  onOpenChange,
  onUpdate,
  onRemove,
}: PassengerCardProps) {
  const title =
    index === 0
      ? PACKAGE_DETAIL.PRIMARY_TRAVELER
      : `${PACKAGE_DETAIL.TRAVELER} ${index + 1}`;

  const childrenAges = customer.children_ages ?? [];

  const handleChildrenCountChange = (newCount: number) => {
    onUpdate("children_count", newCount);
    if (newCount > childrenAges.length) {
      const extended = [
        ...childrenAges,
        ...Array<number>(newCount - childrenAges.length).fill(0),
      ];
      onUpdate("children_ages", extended);
    } else if (newCount < childrenAges.length) {
      onUpdate("children_ages", childrenAges.slice(0, newCount));
    }
  };

  const handleChildAgeChange = (childIndex: number, age: number) => {
    const updated = [...childrenAges];
    updated[childIndex] = age;
    onUpdate("children_ages", updated);
  };

  return (
    <Collapsible open={isOpen} onOpenChange={onOpenChange}>
      <div className="rounded-xl border border-gray-200 bg-gray-50/50">
        {/* Header */}
        <CollapsibleTrigger asChild>
          <button
            type="button"
            className="flex w-full items-center justify-between p-4 text-left hover:bg-gray-50/80"
          >
            <h4 className="flex items-center gap-2 text-sm font-semibold text-gray-900 md:text-base">
              <User className="h-4 w-4 text-primary" />
              {title}
            </h4>
            <div className="flex items-center gap-2">
              {totalCount > 1 && index > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemove();
                  }}
                  className="h-8 text-red-600 hover:bg-red-50 hover:text-red-700"
                >
                  <Trash2 className="mr-1 h-4 w-4" />
                  {PACKAGE_DETAIL.REMOVE}
                </Button>
              )}
              {isOpen ? (
                <ChevronUp className="h-4 w-4 text-gray-500" />
              ) : (
                <ChevronDown className="h-4 w-4 text-gray-500" />
              )}
            </div>
          </button>
        </CollapsibleTrigger>

        <CollapsibleContent>
          <div className="border-t border-gray-200 px-4 pb-4">
            {/* Section 1 – Contact Information */}
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              {/* Full Name */}
              <div>
                <Label
                  htmlFor={`name-${customer.id}`}
                  className="text-sm font-medium text-gray-900"
                >
                  {PACKAGE_DETAIL.FULL_NAME}
                </Label>
                <Input
                  id={`name-${customer.id}`}
                  placeholder={PACKAGE_DETAIL.ENTER_FULL_NAME}
                  value={customer.passenger_name}
                  onChange={(e) => onUpdate("passenger_name", e.target.value)}
                  className="mt-1.5 border-gray-200"
                />
              </div>

              {/* Email Address */}
              <div>
                <Label
                  htmlFor={`email-${customer.id}`}
                  className="text-sm font-medium text-gray-900"
                >
                  {PACKAGE_DETAIL.EMAIL_ADDRESS}
                </Label>
                <div className="relative mt-1.5">
                  <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <Input
                    id={`email-${customer.id}`}
                    type="email"
                    placeholder={PACKAGE_DETAIL.ENTER_EMAIL}
                    value={customer.email}
                    onChange={(e) => onUpdate("email", e.target.value)}
                    className="border-gray-200 pl-10"
                  />
                </div>
              </div>

              {/* Phone Number */}
              <div>
                <Label
                  htmlFor={`phone-${customer.id}`}
                  className="text-sm font-medium text-gray-900"
                >
                  {PACKAGE_DETAIL.PHONE_NUMBER}
                </Label>
                <div className="relative mt-1.5">
                  <Phone className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <Input
                    id={`phone-${customer.id}`}
                    type="tel"
                    placeholder={PACKAGE_DETAIL.ENTER_PHONE}
                    value={customer.phone_number}
                    onChange={(e) => onUpdate("phone_number", e.target.value)}
                    className="border-gray-200 pl-10"
                  />
                </div>
              </div>

              {/* Alternate Contact */}
              <div>
                <Label
                  htmlFor={`alt-contact-${customer.id}`}
                  className="text-sm font-medium text-gray-900"
                >
                  {PACKAGE_DETAIL.ALTERNATE_CONTACT}
                </Label>
                <div className="relative mt-1.5">
                  <UserPlus className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                  <Input
                    id={`alt-contact-${customer.id}`}
                    placeholder={PACKAGE_DETAIL.ENTER_ALTERNATE_CONTACT}
                    value={customer.alternate_contact ?? ""}
                    onChange={(e) =>
                      onUpdate("alternate_contact", e.target.value)
                    }
                    className="border-gray-200 pl-10"
                  />
                </div>
              </div>
            </div>

            {/* Section 2 – Party Composition */}
            <div>
              <h5 className="mb-3 flex items-center gap-2 text-sm font-semibold text-gray-900">
                <Users className="h-4 w-4 text-primary" />
                {PACKAGE_DETAIL.PARTY_COMPOSITION}
              </h5>
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3">
                  <div>
                    <p className="text-sm font-medium text-gray-900">
                      {PACKAGE_DETAIL.NUMBER_OF_ADULTS}
                    </p>
                    <p className="text-xs text-gray-500">
                      {PACKAGE_DETAIL.ADULTS_HELPER}
                    </p>
                  </div>
                  <StepperInput
                    id={`adults-${customer.id}`}
                    value={customer.adults_count ?? 1}
                    min={1}
                    max={20}
                    onChange={(v) => onUpdate("adults_count", v)}
                  />
                </div>
                <div className="flex items-center justify-between rounded-lg border border-gray-200 bg-white px-4 py-3">
                  <div>
                    <p className="text-sm font-medium text-gray-900">
                      {PACKAGE_DETAIL.NUMBER_OF_CHILDREN}
                    </p>
                    <p className="text-xs text-gray-500">
                      {PACKAGE_DETAIL.CHILDREN_HELPER}
                    </p>
                  </div>
                  <StepperInput
                    id={`children-${customer.id}`}
                    value={customer.children_count ?? 0}
                    min={0}
                    max={10}
                    onChange={handleChildrenCountChange}
                  />
                </div>
              </div>
            </div>

            {/* Section 3 – Dynamic Children Age Inputs */}
            {childrenAges.length > 0 && (
              <div>
                <h5 className="mb-3 text-sm font-semibold text-gray-900">
                  {PACKAGE_DETAIL.CHILDREN_AGES_TITLE}
                </h5>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
                  {childrenAges.map((age, i) => {
                    const category = getAgeCategory(age);
                    const badge = AGE_CATEGORY_CONFIG[category];
                    return (
                      <div
                        key={i}
                        className="flex items-center gap-3 rounded-lg border border-gray-200 bg-white px-4 py-3"
                      >
                        <div className="flex-1">
                          <Label
                            htmlFor={`child-age-${customer.id}-${i}`}
                            className="text-xs font-medium text-gray-900"
                          >
                            {PACKAGE_DETAIL.CHILD_LABEL} {i + 1}{" "}
                            {PACKAGE_DETAIL.AGE_LABEL}
                          </Label>
                          <Select
                            value={age.toString()}
                            onValueChange={(v) =>
                              handleChildAgeChange(i, Number(v))
                            }
                          >
                            <SelectTrigger
                              id={`child-age-${customer.id}-${i}`}
                              className="mt-1 border-gray-200"
                            >
                              <SelectValue
                                placeholder={PACKAGE_DETAIL.SELECT_AGE}
                              />
                            </SelectTrigger>
                            <SelectContent>
                              {Array.from({ length: 13 }, (_, n) => (
                                <SelectItem key={n} value={n.toString()}>
                                  {n}{" "}
                                  {n === 1
                                    ? PACKAGE_DETAIL.YEAR
                                    : PACKAGE_DETAIL.YEARS}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <Badge
                          variant={badge.variant}
                          size="sm"
                          className="mt-5 shrink-0"
                        >
                          {badge.label}
                        </Badge>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        </CollapsibleContent>
      </div>
    </Collapsible>
  );
}
