"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { createAdAction, updateAdAction } from "@/lib/actions/ads";
import { AD_SLOTS, AD_SLOT_LIST } from "@/lib/constants/promotions";
import type { Ad } from "@/app/generated/prisma/client";

interface AdFormProps {
  ad?: Ad;
  defaultSlot?: string;
}

export function AdForm({ ad, defaultSlot }: AdFormProps) {
  const isEdit = !!ad;
  const action = isEdit
    ? updateAdAction.bind(null, ad.id)
    : createAdAction;

  const defaultStart = ad?.startAt
    ? new Date(ad.startAt).toISOString().slice(0, 16)
    : "";
  const defaultEnd = ad?.endAt
    ? new Date(ad.endAt).toISOString().slice(0, 16)
    : "";

  return (
    <form action={action} className="max-w-2xl space-y-6">
      <div>
        <Label htmlFor="name">內部名稱 *</Label>
        <Input
          id="name"
          name="name"
          defaultValue={ad?.name}
          required
          placeholder="例：2026 春季合作 — 僅供後台識別"
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="slot">廣告位置 *</Label>
        <select
          id="slot"
          name="slot"
          defaultValue={ad?.slot ?? defaultSlot ?? AD_SLOT_LIST[0].id}
          required
          className="mt-1 flex h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm"
        >
          {AD_SLOT_LIST.map((s) => (
            <option key={s.id} value={s.id}>
              {s.label} — {s.description}
            </option>
          ))}
        </select>
        <p className="mt-1 text-xs text-muted-foreground">
          建議尺寸：{AD_SLOTS[(ad?.slot ?? defaultSlot ?? "homepage_mid") as keyof typeof AD_SLOTS]?.size}
        </p>
      </div>

      <div>
        <Label htmlFor="type">廣告類型 *</Label>
        <select
          id="type"
          name="type"
          defaultValue={ad?.type ?? "image"}
          className="mt-1 flex h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm"
        >
          <option value="image">圖片廣告</option>
          <option value="html">自訂 HTML</option>
        </select>
      </div>

      <div>
        <Label htmlFor="imageUrl">圖片 URL</Label>
        <Input
          id="imageUrl"
          name="imageUrl"
          defaultValue={ad?.imageUrl ?? ""}
          placeholder="https://..."
          className="mt-1"
        />
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="linkUrl">點擊連結</Label>
          <Input
            id="linkUrl"
            name="linkUrl"
            defaultValue={ad?.linkUrl ?? ""}
            placeholder="https://..."
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="altText">圖片替代文字</Label>
          <Input
            id="altText"
            name="altText"
            defaultValue={ad?.altText ?? ""}
            className="mt-1"
          />
        </div>
      </div>

      <div>
        <Label htmlFor="htmlContent">自訂 HTML（僅 html 類型）</Label>
        <Textarea
          id="htmlContent"
          name="htmlContent"
          defaultValue={ad?.htmlContent ?? ""}
          rows={6}
          className="mt-1 font-mono text-sm"
        />
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <div>
          <Label htmlFor="label">廣告標籤</Label>
          <Input
            id="label"
            name="label"
            defaultValue={ad?.label ?? "廣告"}
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="priority">優先級</Label>
          <Input
            id="priority"
            name="priority"
            type="number"
            defaultValue={ad?.priority ?? 0}
            className="mt-1"
          />
        </div>
        <div className="flex items-end pb-1">
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              name="published"
              defaultChecked={ad?.published ?? false}
              className="size-4 rounded border-input"
            />
            已發布
          </label>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="startAt">開始時間（選填）</Label>
          <Input
            id="startAt"
            name="startAt"
            type="datetime-local"
            defaultValue={defaultStart}
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="endAt">結束時間（選填）</Label>
          <Input
            id="endAt"
            name="endAt"
            type="datetime-local"
            defaultValue={defaultEnd}
            className="mt-1"
          />
        </div>
      </div>

      <p className="text-xs text-muted-foreground">
        未發布或不在排程時間內的廣告不會顯示，前台不會留下空白區塊。
      </p>

      <Button type="submit" className="bg-primary text-primary-foreground">
        {isEdit ? "更新廣告" : "建立廣告"}
      </Button>
    </form>
  );
}