"use client";

import { useEffect, useState } from "react";

import { zodResolver } from "@hookform/resolvers/zod";
import { CreditCard, Image as ImageIcon, Layers, Sparkles, Star, Tag } from "lucide-react";
import { Controller, useForm } from "react-hook-form";

import { useDashboardFormSubmit } from "@/app/dashboard/_components/use-dashboard-form-submit";
import { FormPageHeader, FormSaveBar, FormSelect } from "@/app/dashboard/_components/form";
import { FormField } from "@/components/form/form-field";
import { FormSection } from "@/app/dashboard/customers/_components/customer-form/form-section";
import { ErrorBanner } from "@/components/shared/error-banner";
import { ImagePreview } from "@/components/ui/image-preview";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { cn, formatCurrency } from "@/lib/utils";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";

import {
  DEFAULT_CURRENCY,
  PLAN_IMAGE_FIELDS,
  PLAN_STATUS_FORM_OPTIONS,
  PLAN_TYPE_OPTIONS,
  SORT_ORDER_OPTIONS,
  VALIDITY_OPTIONS,
} from "./constants";
import { ImageField } from "./image-field";
import { planCreateDefaults, planCreateSchema, type PlanCreateFormValues } from "./schema";
import type { MembershipPlanDetail } from "../../_lib/membership-plans-server-api";

const LIST_HREF = "/dashboard/plans-orders/membership-plans";

type PlanCreateFormProps = {
  mode?: "create" | "update";
  initial?: MembershipPlanDetail;
  initialErrorMessage?: string | null;
};

function PlanPreview({
  values,
  heroPreview,
}: {
  values: PlanCreateFormValues;
  heroPreview: string | null;
}) {
  const validityLabel = VALIDITY_OPTIONS.find((v) => v.value === values.validity)?.label;
  const priceLabel = values.price ? formatCurrency(values.price) : null;
  const salePriceLabel = values.s_price ? formatCurrency(values.s_price) : null;
  const hasSale =
    salePriceLabel &&
    Number(values.s_price) > 0 &&
    Number(values.s_price) < Number(values.price || 0);

  return (
    <div className="overflow-hidden rounded-xl border bg-card shadow-sm">
      <div className="relative h-24 w-full overflow-hidden bg-linear-to-br from-primary/15 via-primary/5 to-card">
        {heroPreview ? (
          <ImagePreview src={heroPreview} alt="" className="h-full w-full object-cover" />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center text-primary/40">
            <CreditCard className="size-7" />
          </div>
        )}
        {values.recommended ? (
          <span className="absolute top-2 right-2 inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 font-semibold text-[10px] text-amber-800 shadow-sm">
            <Star className="size-2.5" />
            Recommended
          </span>
        ) : null}
      </div>
      <div className="space-y-3 p-4">
        <div className="space-y-1">
          <h3
            className={cn(
              "font-semibold text-base leading-tight",
              !values.name?.trim() && "text-muted-foreground",
            )}
          >
            {values.name?.trim() || "Untitled plan"}
          </h3>
          <p className="text-muted-foreground text-xs leading-relaxed">
            {values.short_description?.trim() || "Short description appears here."}
          </p>
        </div>
        <div className="flex items-baseline gap-2">
          {priceLabel ? (
            <>
              <span className="font-bold text-2xl tabular-nums">{priceLabel}</span>
              {hasSale ? (
                <span className="text-muted-foreground text-xs line-through tabular-nums">{salePriceLabel}</span>
              ) : null}
              {validityLabel ? (
                <span className="text-muted-foreground text-xs">/ {validityLabel}</span>
              ) : null}
            </>
          ) : (
            <span className="text-muted-foreground text-sm italic">Set a price</span>
          )}
        </div>
        {values.no_of_users ? (
          <p className="text-muted-foreground text-xs">Up to {values.no_of_users} user(s)</p>
        ) : null}
        {values.featured_title ? (
          <div className="space-y-1 border-t pt-3">
            <p className="font-medium text-xs">{values.featured_title}</p>
            <p className="line-clamp-3 text-muted-foreground text-xs whitespace-pre-line">
              {values.description?.trim() || "Feature list goes here…"}
            </p>
          </div>
        ) : null}
      </div>
    </div>
  );
}

export function PlanCreateForm({
  mode = "create",
  initial,
  initialErrorMessage = null,
}: PlanCreateFormProps) {
  const isUpdate = mode === "update";

  const form = useForm<PlanCreateFormValues>({
    resolver: zodResolver(planCreateSchema),
    defaultValues: initial?.values ?? planCreateDefaults,
  });

  const errors = form.formState.errors;
  const values = form.watch();
  const planImage = values.plan_image;

  const [heroPreview, setHeroPreview] = useState<string | null>(null);
  useEffect(() => {
    if (!planImage) {
      setHeroPreview(null);
      return;
    }
    const url = URL.createObjectURL(planImage);
    setHeroPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [planImage]);

  const { isSaving, submit } = useDashboardFormSubmit({
    mode: isUpdate ? "update" : "create",
    id: initial?.id,
    createUrl: FRONTEND_ROUTES.plansOrders.membershipPlans.createSubmit,
    updateUrl: FRONTEND_ROUTES.plansOrders.membershipPlans.updateSubmit,
    listHref: LIST_HREF,
    saveFailMessage: "Membership plan could not be saved.",
    messages: {
      createFail: "Membership plan could not be created.",
      updateFail: "Membership plan could not be updated.",
      createSuccess: "Membership plan created.",
      updateSuccess: "Membership plan updated.",
    },
  });

  const onSubmit = form.handleSubmit(async (values) => {
    await submit(values);
  });

  return (
    <form onSubmit={onSubmit} className="m-8 flex flex-col">
      <ErrorBanner message={initialErrorMessage} className="mb-4" />

      <FormPageHeader
        backHref={LIST_HREF}
        parentLabel="Membership plans"
        titleIcon={<Sparkles className="size-4 text-primary" />}
        title={
          isUpdate
            ? `Update ${initial?.values.name?.trim() || "plan"}`
            : values.name?.trim() || "Untitled plan"
        }
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_340px]">
        <div className="space-y-6">
          <FormSection title="Basic information">
            <div className="grid gap-4 md:grid-cols-2">
              <FormField label="Plan name" htmlFor="name" required error={errors.name}>
                <Input id="name" className="h-9" placeholder="e.g. Growth" {...form.register("name")} />
              </FormField>
              <FormField
                label="Multilingual name"
                htmlFor="mul_name"
                description="Optional — JSON or pipe-separated translations."
              >
                <Input
                  id="mul_name"
                  className="h-9"
                  placeholder='e.g. {"en":"Growth","ar":"النمو"}'
                  {...form.register("mul_name")}
                />
              </FormField>
            </div>
            <FormField label="Short description" htmlFor="short_description">
              <Textarea
                id="short_description"
                rows={2}
                placeholder="One-line summary shown on the pricing page."
                {...form.register("short_description")}
              />
            </FormField>
          </FormSection>

          <FormSection title="Pricing">
            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
              <FormField label="Price" htmlFor="price" required error={errors.price}>
                <InputGroup className="h-9">
                  <InputGroupAddon className="border-r bg-muted/40 px-2.5">
                    <InputGroupText className="text-muted-foreground text-xs">
                      {DEFAULT_CURRENCY}
                    </InputGroupText>
                  </InputGroupAddon>
                  <InputGroupInput
                    id="price"
                    type="number"
                    step="0.01"
                    inputMode="decimal"
                    placeholder="0.00"
                    aria-invalid={!!errors.price}
                    {...form.register("price")}
                  />
                </InputGroup>
              </FormField>
              <FormField
                label="Sale price"
                htmlFor="s_price"
                description="Optional — shown struck-through."
                error={errors.s_price}
              >
                <InputGroup className="h-9">
                  <InputGroupAddon className="border-r bg-muted/40 px-2.5">
                    <InputGroupText className="text-muted-foreground text-xs">
                      {DEFAULT_CURRENCY}
                    </InputGroupText>
                  </InputGroupAddon>
                  <InputGroupInput
                    id="s_price"
                    type="number"
                    step="0.01"
                    inputMode="decimal"
                    placeholder="0.00"
                    {...form.register("s_price")}
                  />
                </InputGroup>
              </FormField>
              <FormField label="Validity" htmlFor="validity" required error={errors.validity}>
                <Controller
                  name="validity"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="validity"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select"
                      options={VALIDITY_OPTIONS}
                    />
                  )}
                />
              </FormField>
              <FormField
                label="Number of users"
                htmlFor="no_of_users"
                description="Leave blank for unlimited."
                error={errors.no_of_users}
              >
                <Input
                  id="no_of_users"
                  type="number"
                  inputMode="numeric"
                  className="h-9"
                  placeholder="e.g. 5"
                  {...form.register("no_of_users")}
                />
              </FormField>
              <FormField
                label="Category ID"
                htmlFor="category_id"
                description="Optional customer category."
                error={errors.category_id}
              >
                <Input
                  id="category_id"
                  type="number"
                  inputMode="numeric"
                  className="h-9"
                  placeholder="e.g. 5"
                  {...form.register("category_id")}
                />
              </FormField>
              <FormField
                label="Group ID"
                htmlFor="group_id"
                description="Optional customer group."
                error={errors.group_id}
              >
                <Input
                  id="group_id"
                  type="number"
                  inputMode="numeric"
                  className="h-9"
                  placeholder="e.g. 1"
                  {...form.register("group_id")}
                />
              </FormField>
            </div>
          </FormSection>

          <FormSection title="Marketing">
            <FormField label="Featured title" htmlFor="featured_title">
              <Input id="featured_title" className="h-9" {...form.register("featured_title")} />
            </FormField>
            <FormField
              label="Description"
              htmlFor="description"
              description="Full description — supports rich text in production."
            >
              <Textarea
                id="description"
                rows={6}
                placeholder="• Unlimited projects&#10;• 24/7 priority support&#10;• Advanced analytics"
                {...form.register("description")}
              />
            </FormField>
          </FormSection>

          <FormSection title="Display settings">
            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
              <FormField label="Plan type" htmlFor="plan_type" required error={errors.plan_type}>
                <Controller
                  name="plan_type"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="plan_type"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select type"
                      options={PLAN_TYPE_OPTIONS}
                    />
                  )}
                />
              </FormField>
              <FormField label="Status" htmlFor="status" required error={errors.status}>
                <Controller
                  name="status"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="status"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Select status"
                      options={PLAN_STATUS_FORM_OPTIONS}
                    />
                  )}
                />
              </FormField>
              <FormField label="Sort order" htmlFor="sort_order" required error={errors.sort_order}>
                <Controller
                  name="sort_order"
                  control={form.control}
                  render={({ field }) => (
                    <FormSelect
                      id="sort_order"
                      value={field.value}
                      onChange={field.onChange}
                      placeholder="Order"
                      options={SORT_ORDER_OPTIONS}
                    />
                  )}
                />
              </FormField>
              <div className="space-y-3">
                <Controller
                  name="recommended"
                  control={form.control}
                  render={({ field }) => (
                    <label
                      htmlFor="recommended"
                      className="flex cursor-pointer items-center justify-between rounded-lg border bg-card px-3 py-2"
                    >
                      <div className="space-y-0.5">
                        <div className="flex items-center gap-1.5 font-medium text-sm">
                          <Star className="size-3.5 text-amber-500" />
                          Recommended
                        </div>
                        <p className="text-muted-foreground text-[11px]">Highlight on pricing page.</p>
                      </div>
                      <Switch
                        id="recommended"
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </label>
                  )}
                />
                <Controller
                  name="visible"
                  control={form.control}
                  render={({ field }) => (
                    <label
                      htmlFor="visible"
                      className="flex cursor-pointer items-center justify-between rounded-lg border bg-card px-3 py-2"
                    >
                      <div className="space-y-0.5">
                        <div className="font-medium text-sm">Visible publicly</div>
                        <p className="text-muted-foreground text-[11px]">Show this plan to customers.</p>
                      </div>
                      <Switch
                        id="visible"
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </label>
                  )}
                />
                <Controller
                  name="bundle_only"
                  control={form.control}
                  render={({ field }) => (
                    <label
                      htmlFor="bundle_only"
                      className="flex cursor-pointer items-center justify-between rounded-lg border bg-card px-3 py-2"
                    >
                      <div className="space-y-0.5">
                        <div className="font-medium text-sm">Bundle only</div>
                        <p className="text-muted-foreground text-[11px]">
                          Purchase with bundle only.
                        </p>
                      </div>
                      <Switch
                        id="bundle_only"
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </label>
                  )}
                />
              </div>
            </div>
          </FormSection>

          <FormSection title="Media">
            <div className="mb-2 flex items-center gap-2 text-muted-foreground text-xs">
              <ImageIcon className="size-3.5" />
              Upload up to 5 images for this plan
            </div>
            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {PLAN_IMAGE_FIELDS.map((image) => (
                <Controller
                  key={image.key}
                  name={image.key}
                  control={form.control}
                  render={({ field }) => (
                    <ImageField
                      id={image.key}
                      label={image.label}
                      hint={image.hint}
                      value={field.value ?? null}
                      onChange={field.onChange}
                    />
                  )}
                />
              ))}
            </div>
          </FormSection>
        </div>

        <aside className="space-y-4 lg:sticky lg:top-24 lg:self-start">
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <h2 className="flex items-center gap-2 font-semibold text-sm">
                <Layers className="size-4 text-primary" />
                Live preview
              </h2>
              <span
                className={cn(
                  "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide",
                  values.status === "active"
                    ? "bg-emerald-100 text-emerald-700"
                    : "bg-rose-100 text-rose-700",
                )}
              >
                {values.status}
              </span>
            </div>
            <p className="text-muted-foreground text-[11px]">How this plan will appear to customers.</p>
          </div>
          <PlanPreview values={values} heroPreview={heroPreview} />

          <div className="space-y-2 rounded-lg border bg-muted/30 p-3">
            <div className="flex items-center gap-2 text-muted-foreground text-xs">
              <Tag className="size-3.5" />
              Sort order
            </div>
            <p className="font-mono font-semibold text-sm">#{values.sort_order}</p>
            <p className="text-muted-foreground text-[11px]">Lower numbers appear first on the pricing page.</p>
          </div>
        </aside>
      </div>

      <FormSaveBar
        cancelHref={LIST_HREF}
        isSaving={isSaving}
        saveLabel={isUpdate ? "Save changes" : "Save plan"}
        onReset={
          isUpdate && initial
            ? () => form.reset(initial.values)
            : undefined
        }
      />
    </form>
  );
}
