"use client";

import NextImage from "next/image";
import Link from "next/link";
import { useReducer, useRef } from "react";
import { useRouter } from "next/navigation";
import { uploadProductImage } from "@/actions/products/upload-image";
import { createProduct } from "@/actions/products/create-product";
import { AdminInput,  AdminTextInput, AdminTextarea, AdminSelect  } from "./design-system/AdminFormElements";

async function resizeImage(file: File, maxWidth: number): Promise<ArrayBuffer> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      let { width, height } = img;
      if (width > maxWidth) {
        height = Math.round(height * (maxWidth / width));
        width = maxWidth;
      }
      const canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext("2d")!;
      ctx.drawImage(img, 0, 0, width, height);
      canvas.toBlob((blob) => {
        if (!blob) {
          reject(new Error("Failed to resize image"));
          return;
        }
        blob.arrayBuffer().then((buf) => resolve(buf));
      }, "image/jpeg", 0.85);
    };
    img.onerror = reject;
    img.src = URL.createObjectURL(file);
  });
}

type Props = {
  defaultBrandId?: string;
  brands?: { id: string; name: string }[];
  lockBrand?: boolean;
};

const EMPTY_BRANDS: { id: string; name: string }[] = [];

// --- Reducer state -------------------------------------------------------

type State = {
  loading: boolean;
  error: string | null;
  imagePreview: string | null;
  uploading: boolean;
  uploadError: string | null;
  name: string;
  description: string;
  price: string;
  type: string;
  brandId: string;
  isTaxable: string;
  pickupType: string;
  active: string;
};

type Action =
  | { type: "SET_LOADING"; value: boolean }
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SET_IMAGE_PREVIEW"; value: string | null }
  | { type: "SET_UPLOADING"; value: boolean }
  | { type: "SET_UPLOAD_ERROR"; value: string | null }
  | { type: "SET_FIELD"; field: "name" | "description" | "price" | "type" | "brandId" | "isTaxable" | "pickupType" | "active"; value: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_LOADING":
      return { ...state, loading: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_IMAGE_PREVIEW":
      return { ...state, imagePreview: action.value };
    case "SET_UPLOADING":
      return { ...state, uploading: action.value };
    case "SET_UPLOAD_ERROR":
      return { ...state, uploadError: action.value };
    case "SET_FIELD":
      return { ...state, [action.field]: action.value };
    default:
      return state;
  }
}

function createInitialState(defaultBrandId: string): State {
  return {
    loading: false,
    error: null,
    imagePreview: null,
    uploading: false,
    uploadError: null,
    name: "",
    description: "",
    price: "",
    type: "Pickup",
    brandId: defaultBrandId,
    isTaxable: "true",
    pickupType: "scheduled_stop",
    active: "true",
  };
}

// --- Subcomponent: image uploader ---------------------------------------

type ImageUploaderProps = {
  imagePreview: string | null;
  uploading: boolean;
  uploadError: string | null;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
  onFileSelect: (file: File) => void;
  onRemoveImage: () => void;
};

function ImageUploader({
  imagePreview,
  uploading,
  uploadError,
  fileInputRef,
  onFileSelect,
  onRemoveImage,
}: ImageUploaderProps) {
  return (
    <div>
      <div className="block text-sm font-medium text-[var(--admin-text-primary)]">Product Image</div>
      <p className="text-xs text-[var(--admin-text-muted)] mb-2">JPG, PNG, WebP · 1200px max width · max 5MB (ideally under 2MB)</p>

      <label
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => {
          e.preventDefault();
          const file = e.dataTransfer.files[0];
          if (file) onFileSelect(file);
        }}
        className={`
          flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed p-6 cursor-pointer transition-colors
          ${uploadError ? "border-[var(--admin-danger)]" : "border-[var(--admin-border)] hover:border-[var(--admin-primary)] hover:bg-[var(--admin-bg)]"}
          ${uploading ? "opacity-50 pointer-events-none" : ""}
        `}
      >
        {uploading ? (
          <>
            <div className="h-5 w-5 rounded-full border-2 border-[var(--admin-text-muted)] border-t-transparent animate-spin" />
            <span className="text-sm text-[var(--admin-text-muted)]">Uploading...</span>
          </>
        ) : imagePreview ? (
          <>
            <span className="relative inline-block h-32 w-auto">
              <NextImage src={imagePreview} alt="Product preview" fill style={{ objectFit: "contain" }} className="rounded-lg" />
            </span>
            <span className="text-xs text-[var(--admin-text-muted)]">Click or drop to replace</span>
          </>
        ) : (
          <>
            <svg className="h-8 w-8 text-[var(--admin-text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <span className="text-sm text-[var(--admin-text-muted)]">Drag & drop or click to upload</span>
          </>
        )}
        <input aria-label="File upload"
          ref={fileInputRef}
          type="file"
          accept="image/png,image/jpeg,image/webp"
          className="sr-only"
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) onFileSelect(file);
          }}
        />
      </label>

      {uploadError && <p className="mt-1 text-xs text-[var(--admin-danger)]">{uploadError}</p>}

      {imagePreview && (
        <button
          type="button"
          onClick={onRemoveImage}
          className="mt-2 text-xs text-[var(--admin-danger)] hover:underline"
        >
          Remove image
        </button>
      )}
    </div>
  );
}

// --- Subcomponent: brand selector ---------------------------------------

type BrandSelectorProps = {
  brandId: string;
  brandOptions: { id: string; name: string }[];
  brands: { id: string; name: string }[];
  lockBrand: boolean;
  defaultBrandId: string;
  onChange: (value: string) => void;
};

function BrandSelector({
  brandId,
  brandOptions,
  brands,
  lockBrand,
  defaultBrandId,
  onChange,
}: BrandSelectorProps) {
  const brandSelectOptions = brandOptions.map((b) => ({ value: b.id, label: b.name }));
  return (
    <AdminInput label="Brand" required>
      {lockBrand ? (
        // brand_admin / store_employee — brand is fixed by their admin_users record
        <div className="w-full rounded-lg border border-[var(--admin-border)] bg-[var(--admin-bg)] px-3 py-2.5 text-sm text-[var(--admin-text-primary)]">
          {brandOptions.find((b) => b.id === brandId)?.name ?? brandId}
        </div>
      ) : (
        <AdminSelect
          value={brandId}
          onChange={(e) => onChange(e.target.value)}
          options={[
            { value: "", label: brands.length > 0 ? "Select brand..." : "Loading brands..." },
            ...brandSelectOptions,
          ]}
          disabled={brands.length === 0 && defaultBrandId === ""}
        />
      )}
      {!lockBrand && brands.length === 0 && (
        <p className="mt-1 text-xs text-[var(--admin-text-muted)]">
          Loading available brands — if this persists, check the admin Brands settings.
        </p>
      )}
    </AdminInput>
  );
}

// --- Main component ------------------------------------------------------

export default function NewProductForm({ defaultBrandId = "", brands = EMPTY_BRANDS, lockBrand = false }: Props) {
  const router = useRouter();
  const [state, dispatch] = useReducer(reducer, createInitialState(defaultBrandId));
  const fileInputRef = useRef<HTMLInputElement>(null);
  const pendingImageUrlRef = useRef<string>("");
  const setPendingImageUrl = (v: string) => { pendingImageUrlRef.current = v; };

  // Build the brand options. If the server provided a list, use it; otherwise
  // fall back to the historical hardcoded list so the form still works in
  // environments where getBrands() failed or returned empty.
  const brandOptions = brands.length > 0
    ? brands
    : [
        { id: "64294306-5f42-463d-a5e8-2ad6c81a96de", name: "Tuxedo Corn" },
        { id: "b1cb7a96-d82b-40b1-80b1-d6dd26c56e28", name: "Indian River Direct" },
      ];

  async function handleFileSelect(file: File) {
    const validTypes = ["image/png", "image/jpeg", "image/webp"];
    if (!validTypes.includes(file.type)) {
      dispatch({ type: "SET_UPLOAD_ERROR", value: "Only PNG, JPEG, and WebP images are allowed." });
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      dispatch({ type: "SET_UPLOAD_ERROR", value: "Image must be under 5MB." });
      return;
    }

    // Client-side resize to max 1200px width
    const resizedBuffer = await resizeImage(file, 1200);
    const resizedFile = new File([resizedBuffer], file.name, { type: "image/jpeg" });

    dispatch({ type: "SET_UPLOAD_ERROR", value: null });
    dispatch({ type: "SET_UPLOADING", value: true });
    const result = await uploadProductImage("__NEW__", resizedFile);
    dispatch({ type: "SET_UPLOADING", value: false });

    if (result.success) {
      setPendingImageUrl(result.imageUrl);
      dispatch({ type: "SET_IMAGE_PREVIEW", value: result.imageUrl });
    } else {
      dispatch({ type: "SET_UPLOAD_ERROR", value: result.error ?? "Upload failed." });
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    dispatch({ type: "SET_LOADING", value: true });
    dispatch({ type: "SET_ERROR", value: null });

    // Use pendingImageUrl if image was uploaded, otherwise null
    const imageUrl = pendingImageUrlRef.current || null;

    const result = await createProduct(state.brandId, {
      name: state.name,
      description: state.description,
      price: parseFloat(state.price),
      type: state.type,
      active: state.active === "true",
      image_url: imageUrl,
      is_taxable: state.isTaxable === "true",
      pickup_type: state.pickupType,
    });

    if (!result.success) {
      dispatch({ type: "SET_ERROR", value: result.error ?? "Failed to create product" });
      dispatch({ type: "SET_LOADING", value: false });
      return;
    }

    router.push("/admin/products");
    router.refresh();
  }

  function handleRemoveImage() {
    dispatch({ type: "SET_IMAGE_PREVIEW", value: null });
    setPendingImageUrl("");
  }

  return (
    <form onSubmit={handleSubmit} className="mt-8 max-w-xl space-y-6">
      {state.error && (
        <div className="rounded-xl bg-[var(--admin-danger-soft)] border border-[var(--admin-danger)] p-4 text-[var(--admin-danger)] text-sm">
          {state.error}
        </div>
      )}

      <AdminInput label="Product Name" required>
        <AdminTextInput
          value={state.name}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "name", value: e.target.value })}
          placeholder="e.g. Dozen Sweet Corn"
          autoComplete="off"
        />
      </AdminInput>

      <AdminInput label="Description">
        <AdminTextarea
          value={state.description}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "description", value: e.target.value })}
          rows={3}
          placeholder="e.g. Fresh-picked Olathe sweet corn."
        />
      </AdminInput>

      <div className="grid grid-cols-2 gap-4">
        <AdminInput label="Price ($)" required>
          <AdminTextInput
            type="number"
            step="0.01"
            value={state.price}
            onChange={(e) => dispatch({ type: "SET_FIELD", field: "price", value: e.target.value })}
            placeholder="12.00"
          />
        </AdminInput>

        <AdminInput label="Type" required>
          <AdminSelect
            value={state.type}
            onChange={(e) => dispatch({ type: "SET_FIELD", field: "type", value: e.target.value })}
            options={[
              { value: "Pickup", label: "Pickup" },
              { value: "Shipping", label: "Shipping" },
              { value: "Pickup & Shipping", label: "Pickup & Shipping" },
            ]}
          />
        </AdminInput>
      </div>

      <BrandSelector
        brandId={state.brandId}
        brandOptions={brandOptions}
        brands={brands}
        lockBrand={lockBrand}
        defaultBrandId={defaultBrandId}
        onChange={(v) => dispatch({ type: "SET_FIELD", field: "brandId", value: v })}
      />

      <AdminInput label="Taxable" helpText="Tax applied at checkout for shipping orders in nexus states. Disable for non-taxable items like apparel or cooler boxes.">
        <AdminSelect
          value={state.isTaxable}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "isTaxable", value: e.target.value })}
          options={[
            { value: "true", label: "Yes — taxable (default)" },
            { value: "false", label: "No — non-taxable" },
          ]}
        />
      </AdminInput>

      <AdminInput label="Pickup Type" helpText="Shed pickup uses the product description as the location — no stop required at checkout.">
        <AdminSelect
          value={state.pickupType}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "pickupType", value: e.target.value })}
          options={[
            { value: "scheduled_stop", label: "Scheduled Stop — requires stop selection at checkout" },
            { value: "shed", label: "Shed Pickup — uses description as location" },
          ]}
        />
      </AdminInput>

      <AdminInput label="Active">
        <AdminSelect
          value={state.active}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "active", value: e.target.value })}
          options={[
            { value: "true", label: "Yes — show on storefront" },
            { value: "false", label: "No — hide from storefront" },
          ]}
        />
      </AdminInput>

      <ImageUploader
        imagePreview={state.imagePreview}
        uploading={state.uploading}
        uploadError={state.uploadError}
        fileInputRef={fileInputRef}
        onFileSelect={handleFileSelect}
        onRemoveImage={handleRemoveImage}
      />

      {/* Save button bar — new design tokens */}
      <div className="flex items-center gap-3 pt-4 border-t border-[var(--admin-border-light)]">
        <button
          type="submit"
          disabled={state.loading}
          className="ha-btn-primary"
        >
          {state.loading ? "Creating..." : "Create Product"}
        </button>

        <Link
          href="/admin/products"
          className="ha-btn-ghost"
        >
          Cancel
        </Link>
      </div>
    </form>
  );
}