"use client";

import { useCallback, useState } from "react";

import Link from "next/link";

import { ExternalLink, Plus, ShoppingCart, Trash2, Upload } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { isSailingBookable } from "@/components/admin/cruise-admin-constants";
import { adminRoutes } from "@/lib/admin-routes";
import { getSailingById, saveSailing } from "@/lib/cruise-store";
import type { Sailing, SailingOffer } from "@/types/cruise";

interface SailingPublicPagePanelProps {
  sailingId: string;
}

function readFileAsDataUrl(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.readAsDataURL(file);
  });
}

export function SailingPublicPagePanel({ sailingId }: SailingPublicPagePanelProps) {
  const [refreshKey, setRefreshKey] = useState(0);
  const reload = useCallback(() => setRefreshKey((k) => k + 1), []);
  void refreshKey;

  const sailing = getSailingById(sailingId);
  if (!sailing) return null;

  const update = (patch: Partial<Sailing>) => {
    saveSailing({ ...sailing, ...patch });
    reload();
  };

  const handleBannerUpload = async (file: File) => {
    try {
      const imageUrl = await readFileAsDataUrl(file);
      update({ heroImageUrl: imageUrl });
      toast.success("Banner updated");
    } catch {
      toast.error("Failed to read image");
    }
  };

  const handleGalleryUpload = async (file: File) => {
    try {
      const imageUrl = await readFileAsDataUrl(file);
      update({ galleryImages: [...(sailing.galleryImages ?? []), imageUrl] });
      toast.success("Photo added to gallery");
    } catch {
      toast.error("Failed to read image");
    }
  };

  const removeGalleryImage = (index: number) => {
    const galleryImages = [...(sailing.galleryImages ?? [])];
    galleryImages.splice(index, 1);
    update({ galleryImages });
    toast.success("Photo removed");
  };

  const addOffer = () => {
    const offer: SailingOffer = {
      id: `offer-${Date.now()}`,
      title: "New offer",
      description: "Describe the promotion or package.",
      badge: "Limited",
      priceLabel: "From $99",
    };
    update({ offers: [...(sailing.offers ?? []), offer] });
  };

  const updateOffer = (id: string, patch: Partial<SailingOffer>) => {
    update({
      offers: (sailing.offers ?? []).map((o) => (o.id === id ? { ...o, ...patch } : o)),
    });
  };

  const removeOffer = (id: string) => {
    update({ offers: (sailing.offers ?? []).filter((o) => o.id !== id) });
    toast.success("Offer removed");
  };

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-muted/30 px-4 py-3">
        <p className="text-sm">
          Marketing landing page — guests browse here, then enter checkout via &quot;Book now&quot;.
        </p>
        <div className="flex flex-wrap gap-2">
          <Button variant="secondary" size="sm" asChild>
            <Link href={adminRoutes.publicEvent(sailing.slug)} target="_blank" rel="noreferrer">
              <ExternalLink className="size-4" />
              Preview public page
            </Link>
          </Button>
          <Button variant="outline" size="sm" asChild disabled={!isSailingBookable(sailing.status)}>
            <Link href={adminRoutes.publicBook(sailing.id)} target="_blank" rel="noreferrer">
              <ShoppingCart className="size-4" />
              Preview booking wizard
            </Link>
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Banner & hero</CardTitle>
          <CardDescription>
            Main banner image and headline copy for the public event page at{" "}
            <a href={adminRoutes.publicEvent(sailing.slug)} target="_blank" rel="noreferrer" className="text-primary hover:underline">
              /events/{sailing.slug}
            </a>
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          {sailing.heroImageUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={sailing.heroImageUrl} alt="Banner" className="h-48 w-full rounded-lg object-cover" />
          ) : (
            <div className="flex h-48 items-center justify-center rounded-lg border border-dashed text-muted-foreground text-sm">
              No banner image — upload one below
            </div>
          )}
          <Label className="cursor-pointer">
            <div className="flex items-center justify-center gap-2 rounded-lg border border-dashed p-4 text-muted-foreground text-sm hover:bg-muted/50">
              <Upload className="size-4" />
              Upload banner image
            </div>
            <Input
              type="file"
              accept="image/*"
              className="hidden"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (file) await handleBannerUpload(file);
                e.target.value = "";
              }}
            />
          </Label>
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="grid gap-1.5">
              <Label>Hero title</Label>
              <Input
                value={sailing.heroTitle}
                onChange={(e) => update({ heroTitle: e.target.value })}
              />
            </div>
            <div className="grid gap-1.5">
              <Label>Hero subtitle</Label>
              <Input
                value={sailing.heroSubtitle}
                onChange={(e) => update({ heroSubtitle: e.target.value })}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-2">
          <div>
            <CardTitle className="text-base">Event gallery</CardTitle>
            <CardDescription>Multiple photos shown on the public page — parties, venues, past sailings.</CardDescription>
          </div>
          <Label className="cursor-pointer">
            <Button variant="secondary" size="sm" asChild>
              <span>
                <Upload className="size-4" />
                Add photo
              </span>
            </Button>
            <Input
              type="file"
              accept="image/*"
              className="hidden"
              onChange={async (e) => {
                const file = e.target.files?.[0];
                if (file) await handleGalleryUpload(file);
                e.target.value = "";
              }}
            />
          </Label>
        </CardHeader>
        <CardContent>
          {(sailing.galleryImages ?? []).length > 0 ? (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {(sailing.galleryImages ?? []).map((url, i) => (
                <div key={`${url.slice(0, 32)}-${i}`} className="group relative overflow-hidden rounded-lg border">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={url} alt={`Gallery ${i + 1}`} className="aspect-[4/3] w-full object-cover" />
                  <Button
                    variant="destructive"
                    size="icon"
                    className="absolute top-2 right-2 size-8 opacity-0 transition-opacity group-hover:opacity-100"
                    onClick={() => removeGalleryImage(i)}
                  >
                    <Trash2 className="size-4" />
                  </Button>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">No gallery photos yet.</p>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Description</CardTitle>
          <CardDescription>Long-form copy about the event, lineup, and experience.</CardDescription>
        </CardHeader>
        <CardContent>
          <Textarea
            value={sailing.description ?? ""}
            onChange={(e) => update({ description: e.target.value })}
            rows={6}
            placeholder="Tell guests what makes this sailing unique…"
          />
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-2">
          <div>
            <CardTitle className="text-base">Marketing highlights</CardTitle>
            <CardDescription>
              Display cards on the public page only — not checkout discounts. Use the Promo codes tab for wizard codes.
            </CardDescription>
          </div>
          <Button variant="secondary" size="sm" onClick={addOffer}>
            <Plus className="size-4" />
            Add offer
          </Button>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          {(sailing.offers ?? []).length === 0 ? (
            <p className="text-muted-foreground text-sm">No offers configured.</p>
          ) : (
            (sailing.offers ?? []).map((offer) => (
              <div key={offer.id} className="rounded-lg border p-4">
                <div className="mb-3 flex items-start justify-between gap-2">
                  <p className="font-medium text-sm">Offer</p>
                  <Button variant="ghost" size="icon" className="size-8 text-destructive" onClick={() => removeOffer(offer.id)}>
                    <Trash2 className="size-4" />
                  </Button>
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="grid gap-1.5">
                    <Label>Title</Label>
                    <Input value={offer.title} onChange={(e) => updateOffer(offer.id, { title: e.target.value })} />
                  </div>
                  <div className="grid gap-1.5">
                    <Label>Badge</Label>
                    <Input value={offer.badge ?? ""} onChange={(e) => updateOffer(offer.id, { badge: e.target.value })} placeholder="Early bird" />
                  </div>
                  <div className="grid gap-1.5 sm:col-span-2">
                    <Label>Description</Label>
                    <Textarea value={offer.description} onChange={(e) => updateOffer(offer.id, { description: e.target.value })} rows={2} />
                  </div>
                  <div className="grid gap-1.5">
                    <Label>Price label</Label>
                    <Input value={offer.priceLabel ?? ""} onChange={(e) => updateOffer(offer.id, { priceLabel: e.target.value })} placeholder="Save $200" />
                  </div>
                </div>
              </div>
            ))
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Public page sections</CardTitle>
          <CardDescription>Choose what guests see on the landing page.</CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          <div className="flex items-center justify-between gap-4">
            <div>
              <p className="font-medium text-sm">Cabin catalog</p>
              <p className="text-muted-foreground text-xs">Show category availability and pricing overview</p>
            </div>
            <Switch
              checked={sailing.publicShowCatalog !== false}
              onCheckedChange={(checked) => update({ publicShowCatalog: checked })}
            />
          </div>
          <div className="flex items-center justify-between gap-4">
            <div>
              <p className="font-medium text-sm">Deck plans</p>
              <p className="text-muted-foreground text-xs">Inherited from the linked cruise ship layout</p>
            </div>
            <Switch
              checked={sailing.publicShowDeckPlans !== false}
              onCheckedChange={(checked) => update({ publicShowDeckPlans: checked })}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
