"use client";

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 { Textarea } from "@/components/ui/textarea";
import { createVenueAction, updateVenueAction } from "@/lib/actions/venues";
import { ACCESS_LEVELS } from "@/lib/utils";
import type { Venue, City } from "@/lib/types";
import { parseJsonArray } from "@/lib/utils";

interface VenueFormProps {
  cities: City[];
  venueCategories: { nameZh: string }[];
  venue?: Venue & { city: City };
}

export function VenueForm({ cities, venueCategories, venue }: VenueFormProps) {
  const isEdit = !!venue;
  const action = isEdit
    ? updateVenueAction.bind(null, venue.id)
    : createVenueAction;

  return (
    <form action={action} className="max-w-2xl space-y-6">
      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="nameZh">中文名稱 *</Label>
          <Input
            id="nameZh"
            name="nameZh"
            defaultValue={venue?.nameZh}
            required
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="nameEn">英文名稱</Label>
          <Input
            id="nameEn"
            name="nameEn"
            defaultValue={venue?.nameEn ?? ""}
            className="mt-1"
          />
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="slug">Slug *</Label>
          <Input
            id="slug"
            name="slug"
            defaultValue={venue?.slug}
            required
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="cityId">城市 *</Label>
          <select
            id="cityId"
            name="cityId"
            defaultValue={venue?.cityId}
            required
            className="mt-1 flex h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm"
          >
            {cities.map((c) => (
              <option key={c.id} value={c.id}>
                {c.nameZh}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div>
        <Label htmlFor="type">類型 *</Label>
        <select
          id="type"
          name="type"
          defaultValue={venue?.type ?? venueCategories[0]?.nameZh}
          required
          className="mt-1 flex h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm"
        >
          {venueCategories.map((t) => (
            <option key={t.nameZh} value={t.nameZh}>
              {t.nameZh}
            </option>
          ))}
        </select>
        <p className="mt-1 text-xs text-muted-foreground">
          <a href="/admin/categories?kind=venue" className="text-primary hover:underline">
            管理場地分類 →
          </a>
        </p>
      </div>

      <div>
        <Label htmlFor="description">場地介紹 *</Label>
        <Textarea
          id="description"
          name="description"
          defaultValue={venue?.description}
          required
          rows={5}
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="nightWalkTips">老司機夜遊心得 *</Label>
        <Textarea
          id="nightWalkTips"
          name="nightWalkTips"
          defaultValue={venue?.nightWalkTips}
          required
          rows={4}
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="safetyReminders">安全提醒（每行一條）</Label>
        <Textarea
          id="safetyReminders"
          name="safetyReminders"
          defaultValue={
            venue ? parseJsonArray(venue.safetyReminders).join("\n") : ""
          }
          rows={4}
          className="mt-1"
        />
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="address">地址 *</Label>
          <Input
            id="address"
            name="address"
            defaultValue={venue?.address}
            required
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="hours">營業時間 *</Label>
          <Input
            id="hours"
            name="hours"
            defaultValue={venue?.hours}
            required
            className="mt-1"
          />
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="priceRange">價格範圍 *</Label>
          <Input
            id="priceRange"
            name="priceRange"
            defaultValue={venue?.priceRange}
            required
            placeholder="฿500 – ฿2,000 / 人"
            className="mt-1"
          />
        </div>
        <div>
          <Label htmlFor="contact">聯絡方式</Label>
          <Input
            id="contact"
            name="contact"
            defaultValue={venue?.contact ?? ""}
            className="mt-1"
          />
        </div>
      </div>

      <div>
        <Label htmlFor="facilities">設施標籤（逗號分隔）</Label>
        <Input
          id="facilities"
          name="facilities"
          defaultValue={
            venue ? parseJsonArray(venue.facilities).join(", ") : ""
          }
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="images">圖片 URL（每行一張）</Label>
        <Textarea
          id="images"
          name="images"
          defaultValue={venue ? parseJsonArray(venue.images).join("\n") : ""}
          rows={3}
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="accessLevel">存取權限</Label>
        <select
          id="accessLevel"
          name="accessLevel"
          defaultValue={venue?.accessLevel ?? "free"}
          className="mt-1 flex h-8 w-full rounded-lg border border-input bg-transparent px-2.5 text-sm"
        >
          {ACCESS_LEVELS.map((l) => (
            <option key={l.value} value={l.value}>
              {l.label}
            </option>
          ))}
        </select>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <div>
          <Label htmlFor="rating">評分 (0-5)</Label>
          <Input
            id="rating"
            name="rating"
            type="number"
            step="0.1"
            min="0"
            max="5"
            defaultValue={venue?.rating ?? ""}
            className="mt-1"
          />
        </div>
        <div className="flex items-end gap-6 pb-1">
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              name="featured"
              defaultChecked={venue?.featured}
              className="size-4 rounded border-input"
            />
            精選場地
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              name="published"
              defaultChecked={venue?.published ?? true}
              className="size-4 rounded border-input"
            />
            已發布
          </label>
        </div>
      </div>

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