"use client";

import type { Brand, Cruise, PaymentPlanType, PaymentScheduleTemplate, SailingOffer, SailingStatus } from "@/types/cruise";

import { EventAddOnPicker } from "@/components/admin/event-add-on-picker";
import { EventPromoCodePicker } from "@/components/admin/event-promo-code-picker";
import {
  EventItineraryFields,
  EventPaymentConfigFields,
  EventPublicMediaFields,
} from "@/components/admin/event-form-sections";
import { defaultPaymentTemplate } from "@/components/admin/cruise-admin-constants";
import { ALL_PAYMENT_PLANS } from "@/lib/event-form-utils";
import { sailingStatusLabel } from "@/components/admin/cruise-admin-constants";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";

export type EventFormState = {
  brandId: string;
  cruiseId: string;
  name: string;
  slug: string;
  departureDate: string;
  returnDate: string;
  departurePort: string;
  basePrice: string;
  depositAmount: string;
  balanceDueDate: string;
  cabinSelectionUpgradeFee: string;
  status: SailingStatus;
  heroTitle: string;
  heroSubtitle: string;
  description: string;
  heroImageUrl: string;
  galleryImages: string[];
  offers: SailingOffer[];
  publicShowCatalog: boolean;
  publicShowDeckPlans: boolean;
  itinerary: { day: number; title: string; description: string }[];
  allowPartialPayments: boolean;
  minPartialPayment: string;
  allowedPaymentPlans: PaymentPlanType[];
  paymentScheduleTemplates: PaymentScheduleTemplate[];
  promoIds: string[];
  linkedAddOnIds: string[];
  importInventory: boolean;
};

type EventFormFieldsProps = {
  form: EventFormState;
  onChange: (patch: Partial<EventFormState>) => void;
  brands: Brand[];
  cruises: Cruise[];
  isNew: boolean;
};

export function EventFormFields({ form, onChange, brands, cruises, isNew }: EventFormFieldsProps) {
  const set = (patch: Partial<EventFormState>) => onChange(patch);

  return (
    <div className="flex flex-col gap-5">
      <section className="space-y-4">
        <p className="font-medium text-sm">Event details</p>
        <div className="grid gap-1.5">
          <Label>Brand *</Label>
          <Select
            value={brands.some((b) => b.id === form.brandId) ? form.brandId : undefined}
            onValueChange={(v) => set({ brandId: v })}
          >
            <SelectTrigger>
              <SelectValue placeholder="Select brand" />
            </SelectTrigger>
            <SelectContent>
              {brands.map((b) => (
                <SelectItem key={b.id} value={b.id}>
                  {b.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-1.5">
          <Label>Cruise ship *</Label>
          <Select
            value={cruises.some((c) => c.id === form.cruiseId) ? form.cruiseId : undefined}
            onValueChange={(v) => set({ cruiseId: v })}
          >
            <SelectTrigger>
              <SelectValue placeholder="Select cruise" />
            </SelectTrigger>
            <SelectContent>
              {cruises.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.name} ({c.cruiseLine})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-1.5">
          <Label>Event name *</Label>
          <Input value={form.name} onChange={(e) => set({ name: e.target.value })} />
        </div>
        <div className="grid gap-1.5">
          <Label>Slug *</Label>
          <Input value={form.slug} onChange={(e) => set({ slug: e.target.value })} />
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div className="grid gap-1.5">
            <Label>Departure</Label>
            <Input type="date" value={form.departureDate} onChange={(e) => set({ departureDate: e.target.value })} />
          </div>
          <div className="grid gap-1.5">
            <Label>Return</Label>
            <Input type="date" value={form.returnDate} onChange={(e) => set({ returnDate: e.target.value })} />
          </div>
        </div>
        <div className="grid gap-1.5">
          <Label>Departure port</Label>
          <Input value={form.departurePort} onChange={(e) => set({ departurePort: e.target.value })} />
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div className="grid gap-1.5">
            <Label>Base price</Label>
            <Input type="number" value={form.basePrice} onChange={(e) => set({ basePrice: e.target.value })} />
          </div>
          <div className="grid gap-1.5">
            <Label>Deposit</Label>
            <Input type="number" value={form.depositAmount} onChange={(e) => set({ depositAmount: e.target.value })} />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div className="grid gap-1.5">
            <Label>Balance due</Label>
            <Input type="date" value={form.balanceDueDate} onChange={(e) => set({ balanceDueDate: e.target.value })} />
          </div>
          <div className="grid gap-1.5">
            <Label>Cabin upgrade fee</Label>
            <Input
              type="number"
              value={form.cabinSelectionUpgradeFee}
              onChange={(e) => set({ cabinSelectionUpgradeFee: e.target.value })}
            />
          </div>
        </div>
        <div className="grid gap-1.5">
          <Label>Status</Label>
          <Select value={form.status} onValueChange={(v) => set({ status: v as SailingStatus })}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {(Object.keys(sailingStatusLabel) as SailingStatus[]).map((s) => (
                <SelectItem key={s} value={s}>
                  {sailingStatusLabel[s]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <p className="text-muted-foreground text-xs">Published makes the public page live for guests.</p>
        </div>
        {isNew && (
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={form.importInventory}
              onChange={(e) => set({ importInventory: e.target.checked })}
              className="rounded border"
            />
            Import cabin layout from selected cruise
          </label>
        )}
      </section>

      <Separator />

      <section className="space-y-4">
        <p className="font-medium text-sm">Public page copy</p>
        <div className="grid gap-1.5">
          <Label>Hero title</Label>
          <Input value={form.heroTitle} onChange={(e) => set({ heroTitle: e.target.value })} />
        </div>
        <div className="grid gap-1.5">
          <Label>Hero subtitle</Label>
          <Input value={form.heroSubtitle} onChange={(e) => set({ heroSubtitle: e.target.value })} />
        </div>
        <div className="grid gap-1.5">
          <Label>Description</Label>
          <Textarea
            rows={4}
            value={form.description}
            onChange={(e) => set({ description: e.target.value })}
            placeholder="About this event…"
          />
        </div>
      </section>

      <Separator />

      <section className="space-y-4">
        <p className="font-medium text-sm">Checkout options</p>
        <EventAddOnPicker
          selectedAddOnIds={form.linkedAddOnIds}
          onChange={(linkedAddOnIds) => set({ linkedAddOnIds })}
        />
        <EventPromoCodePicker selectedPromoIds={form.promoIds} onChange={(promoIds) => set({ promoIds })} />
      </section>

      <EventPublicMediaFields form={form} onChange={set} />
      <EventItineraryFields form={form} onChange={set} />
      <EventPaymentConfigFields form={form} onChange={set} />
    </div>
  );
}

export function emptyEventForm(partial?: Partial<EventFormState>): EventFormState {
  return {
    brandId: "",
    cruiseId: "",
    name: "",
    slug: "",
    departureDate: "",
    returnDate: "",
    departurePort: "",
    basePrice: "1299",
    depositAmount: "250",
    balanceDueDate: "",
    cabinSelectionUpgradeFee: "75",
    status: "draft",
    heroTitle: "",
    heroSubtitle: "",
    description: "",
    heroImageUrl: "",
    galleryImages: [],
    offers: [],
    publicShowCatalog: true,
    publicShowDeckPlans: true,
    itinerary: [{ day: 1, title: "Departure", description: "Board the ship" }],
    allowPartialPayments: true,
    minPartialPayment: "50",
    allowedPaymentPlans: [...ALL_PAYMENT_PLANS],
    paymentScheduleTemplates: [defaultPaymentTemplate],
    promoIds: [],
    linkedAddOnIds: [],
    importInventory: true,
    ...partial,
  };
}
