"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { SectionCard } from "../components/product-form/SectionCard";
import {
  BasicInfoSection,
  MediaSection,
  PricingInventorySection,
  DescriptionSection,
  SpecificationsSection,
  SEOSection,
} from "../components/product-form";
import type {
  ProductFormData,
  ProductCategory,
  ProductBrand,
  ProductTag,
} from "../types/product-form";
import { defaultProductFormData } from "../types/product-form";
import { createProduct, updateProduct } from "@/lib/actions/products";
import {
  RiArrowLeftLine,
  RiSaveLine,
  RiEyeLine,
  RiFileCopyLine,
} from "@remixicon/react";

/**
 * Tag options offered by the Basics picker. Tag rows themselves are created
 * on demand (connectOrCreate) when a product is saved with a new tag.
 */
const AVAILABLE_TAGS: ProductTag[] = [
  { id: "tag-new", name: "New Arrival", color: "green" },
  { id: "tag-sale", name: "On Sale", color: "red" },
  { id: "tag-bestseller", name: "Best Seller", color: "yellow" },
  { id: "tag-featured", name: "Featured", color: "blue" },
  { id: "tag-gaming", name: "Gaming", color: "purple" },
  { id: "tag-workstation", name: "Workstation", color: "orange" },
  { id: "tag-budget", name: "Budget Friendly", color: "gray" },
  { id: "tag-premium", name: "Premium", color: "gold" },
];

interface AddProductPageClientProps {
  isEditing: boolean;
  productId: string | null;
  /** Pre-filled form for edit mode; null for a brand-new product. */
  initialData: ProductFormData | null;
  categories: ProductCategory[];
  brands: ProductBrand[];
}

export function AddProductPageClient({
  isEditing,
  productId,
  initialData,
  categories,
  brands,
}: AddProductPageClientProps) {
  const router = useRouter();

  // Form state (server-fetched edit data seeds the form; otherwise defaults)
  const [formData, setFormData] = React.useState<ProductFormData>(
    initialData ?? defaultProductFormData,
  );
  const [errors, setErrors] = React.useState<
    Partial<Record<keyof ProductFormData, string>>
  >({});
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [activeSection, setActiveSection] = React.useState<string>("basic");

  const handleChange = (data: Partial<ProductFormData>) => {
    setFormData((prev) => ({ ...prev, ...data }));
    // Clear error for changed fields
    const changedKeys = Object.keys(data) as (keyof ProductFormData)[];
    setErrors((prev) => {
      const newErrors = { ...prev };
      changedKeys.forEach((key) => delete newErrors[key]);
      return newErrors;
    });
  };

  const validateForm = (): boolean => {
    const newErrors: Partial<Record<keyof ProductFormData, string>> = {};

    if (!formData.name.trim()) {
      newErrors.name = "Product name is required";
    }

    if (!formData.sku.trim()) {
      newErrors.sku = "SKU is required";
    }

    if (!formData.categoryId) {
      newErrors.categoryId = "Category is required";
    }

    if (formData.pricing.purchasePrice < 0) {
      newErrors.pricing = "Purchase price cannot be negative";
    }

    if (formData.pricing.sellingPrice < 0) {
      newErrors.pricing = "Selling price cannot be negative";
    }

    if (
      formData.pricing.sellingPrice > 0 &&
      formData.pricing.purchasePrice > formData.pricing.sellingPrice
    ) {
      newErrors.pricing = "Purchase price should not exceed selling price";
    }

    if (formData.inventory.stockQuantity < 0) {
      newErrors.inventory = "Stock quantity cannot be negative";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async (status: ProductFormData["status"] = "draft") => {
    if (!validateForm()) {
      // Scroll to first error
      const firstErrorKey = Object.keys(errors)[0];
      const errorElement = document.getElementById(`field-${firstErrorKey}`);
      if (errorElement) {
        errorElement.scrollIntoView({ behavior: "smooth", block: "center" });
      }
      return;
    }

    setIsSubmitting(true);

    const result =
      isEditing && productId
        ? await updateProduct(productId, formData, status)
        : await createProduct(formData, status);

    if (!result.ok) {
      setIsSubmitting(false);
      alert(result.error);
      return;
    }

    setIsSubmitting(false);
    alert(result.message);
    router.push("/admin/dashboard/inventory");
  };

  const handleDuplicate = () => {
    const newData = {
      ...formData,
      name: `${formData.name} (Copy)`,
      sku: `${formData.sku}-COPY-${Date.now()}`,
      status: "draft" as const,
      createdAt: undefined,
      updatedAt: undefined,
    };
    setFormData(newData);
    alert("Product duplicated! You can now edit the copy.");
  };

  const handleCancel = () => {
    router.back();
  };

  const sections = [
    {
      id: "basic",
      title: "Basic Information",
      description: "Product name, brand, category, and tags",
    },
    {
      id: "media",
      title: "Product Media",
      description: "Product images, promotional images, and videos",
    },
    {
      id: "pricing",
      title: "Pricing & Inventory",
      description:
        "Purchase price, selling price, stock, and inventory settings",
    },
    {
      id: "description",
      title: "Product Description",
      description: "Overview, highlights, and detailed description",
    },
    {
      id: "specs",
      title: "Specifications",
      description: "Key features, technical specifications, and FAQs",
    },
    {
      id: "seo",
      title: "SEO Settings",
      description: "Meta tags, Open Graph, and search optimization",
    },
  ];

  return (
    <div className="flex flex-col gap-6">
      {/* Page Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">
            {isEditing ? "Edit Product" : "Add New Product"}
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            {isEditing
              ? "Update product details and settings"
              : "Create a new product for your inventory"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleCancel}>
            <RiArrowLeftLine className="h-4 w-4 mr-1.5" />
            Back to Inventory
          </Button>
          <Button variant="outline" size="sm" onClick={handleDuplicate}>
            <RiFileCopyLine className="h-4 w-4 mr-1.5" />
            Duplicate
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => handleSave("draft")}
            disabled={isSubmitting}
          >
            <RiSaveLine className="h-4 w-4 mr-1.5" />
            Save Draft
          </Button>
          <Button
            size="sm"
            onClick={() => handleSave("active")}
            disabled={isSubmitting}
          >
            <RiEyeLine className="h-4 w-4 mr-1.5" />
            {isSubmitting ? "Publishing..." : "Publish"}
          </Button>
        </div>
      </div>

      {/* Mobile Section Tabs */}
      <div className="md:hidden overflow-x-auto pb-2">
        <nav className="flex gap-2" aria-label="Form sections">
          {sections.map((section) => (
            <button
              key={section.id}
              type="button"
              onClick={() => setActiveSection(section.id)}
              className={cn(
                "flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl transition-all whitespace-nowrap shrink-0",
                activeSection === section.id
                  ? "bg-primary text-primary-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted",
              )}
            >
              {section.title}
            </button>
          ))}
        </nav>
      </div>

      {/* Form Sections */}
      <form onSubmit={(e) => e.preventDefault()} className="space-y-6">
        {/* Section 1: Basic Information */}
        <SectionCard
          title="Basic Information"
          description="Product name, brand, category, and tags"
          collapsible
          defaultOpen={activeSection === "basic"}
        >
          <BasicInfoSection
            data={formData}
            onChange={handleChange}
            categories={categories}
            brands={brands}
            availableTags={AVAILABLE_TAGS}
            errors={errors}
          />
        </SectionCard>

        {/* Section 2: Product Media */}
        <SectionCard
          title="Product Media"
          description="Product images, promotional images, and videos"
          collapsible
          defaultOpen={activeSection === "media"}
        >
          <MediaSection
            data={formData}
            onChange={handleChange}
            errors={errors}
          />
        </SectionCard>

        {/* Section 3: Pricing & Inventory */}
        <SectionCard
          title="Pricing & Inventory"
          description="Purchase price, selling price, stock, and inventory settings"
          collapsible
          defaultOpen={activeSection === "pricing"}
        >
          <PricingInventorySection
            data={formData}
            onChange={handleChange}
            errors={errors}
            currency="BDT"
          />
        </SectionCard>

        {/* Section 4: Product Description */}
        <SectionCard
          title="Product Description"
          description="Overview, highlights, and detailed description"
          collapsible
          defaultOpen={activeSection === "description"}
        >
          <DescriptionSection
            data={formData}
            onChange={handleChange}
            errors={errors}
          />
        </SectionCard>

        {/* Section 5: Specifications */}
        <SectionCard
          title="Specifications"
          description="Key features, technical specifications, and FAQs"
          collapsible
          defaultOpen={activeSection === "specs"}
        >
          <SpecificationsSection
            data={formData}
            onChange={handleChange}
            errors={errors}
          />
        </SectionCard>

        {/* Section 6: SEO Settings */}
        <SectionCard
          title="SEO Settings"
          description="Meta tags, Open Graph, and search optimization"
          collapsible
          defaultOpen={activeSection === "seo"}
        >
          <SEOSection
            data={formData}
            onChange={handleChange}
            errors={errors}
            autoGenerateFromName={formData.name}
          />
        </SectionCard>

        {/* Bottom Action Bar */}
        <div className="sticky bottom-0 flex items-center justify-between gap-4 border-t border-border bg-background/95 backdrop-blur-sm px-4 py-4 md:px-0">
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={handleCancel}>
              <RiArrowLeftLine className="h-4 w-4 mr-1.5" />
              Cancel
            </Button>
            <Button variant="outline" size="sm" onClick={handleDuplicate}>
              <RiFileCopyLine className="h-4 w-4 mr-1.5" />
              Duplicate
            </Button>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleSave("draft")}
              disabled={isSubmitting}
            >
              <RiSaveLine className="h-4 w-4 mr-1.5" />
              Save Draft
            </Button>
            <Button
              size="sm"
              onClick={() => handleSave("active")}
              disabled={isSubmitting}
            >
              <RiEyeLine className="h-4 w-4 mr-1.5" />
              {isSubmitting ? "Publishing..." : "Publish"}
            </Button>
          </div>
        </div>
      </form>
    </div>
  );
}