"use client";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { FormField, NumberInputField, InputField } from "./FormField";
import type { ProductFormData } from "../../types/product-form";

interface PricingInventorySectionProps {
  data: ProductFormData;
  onChange: (data: Partial<ProductFormData>) => void;
  errors?: Partial<Record<keyof ProductFormData, string>>;
  currency?: string;
}

export function PricingInventorySection({
  data,
  onChange,
  errors = {},
  currency = "BDT",
}: PricingInventorySectionProps) {
  const handleNestedChange = <T extends object>(
    parentField: keyof ProductFormData,
    nestedField: keyof T,
    value: unknown,
  ) => {
    const current = data[parentField] as T;
    onChange({
      [parentField]: { ...current, [nestedField]: value },
    } as Partial<ProductFormData>);
  };

  // Calculate profit for display
  const profitPerUnit = data.pricing.sellingPrice - data.pricing.purchasePrice;
  const profitMargin =
    data.pricing.sellingPrice > 0
      ? ((profitPerUnit / data.pricing.sellingPrice) * 100).toFixed(1)
      : 0;

  const currencySymbols: Record<string, string> = {
    BDT: "৳",
    USD: "$",
    EUR: "€",
    GBP: "£",
    INR: "₹",
  };

  const currencySymbol = currencySymbols[currency] || currency;

  return (
    <div className="space-y-8">
      {/* Pricing Section */}
      <section className="space-y-6">
        <header>
          <h3 className="text-lg font-semibold text-foreground">Pricing</h3>
          <p className="text-sm text-muted-foreground mt-1">
            Set purchase and selling prices, discounts, and view profit margins
          </p>
        </header>

        {/* Purchase Price - Critical for profit calculation */}
        <NumberInputField
          label="Purchase Price (Cost)"
          description="Cost price per unit — used to calculate profit margins"
          error={errors.pricing as string}
          required
          value={data.pricing.purchasePrice}
          onChange={(e) =>
            handleNestedChange(
              "pricing",
              "purchasePrice",
              parseFloat(e.target.value) || 0,
            )
          }
          min={0}
          step={0.01}
          prefix={currencySymbol}
          className="w-full max-w-xs"
        />

        {/* Selling Price & Compare-at Price */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <NumberInputField
            label="Selling Price"
            description="Regular selling price per unit"
            error={errors.pricing as string}
            required
            value={data.pricing.sellingPrice}
            onChange={(e) =>
              handleNestedChange(
                "pricing",
                "sellingPrice",
                parseFloat(e.target.value) || 0,
              )
            }
            min={0}
            step={0.01}
            prefix={currencySymbol}
            className="w-full"
          />

          <NumberInputField
            label="Compare-at Price"
            description="Original price shown crossed out (for sale pricing)"
            value={data.pricing.compareAtPrice || ""}
            onChange={(e) =>
              handleNestedChange(
                "pricing",
                "compareAtPrice",
                e.target.value ? parseFloat(e.target.value) : undefined,
              )
            }
            min={0}
            step={0.01}
            prefix={currencySymbol}
            className="w-full"
          />
        </div>

        {/* Discount */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <NumberInputField
            label="Discount Percentage"
            description="Discount percentage (auto-calculated if compare-at price is set)"
            value={data.pricing.discountPercent || ""}
            onChange={(e) =>
              handleNestedChange(
                "pricing",
                "discountPercent",
                e.target.value ? parseFloat(e.target.value) : undefined,
              )
            }
            min={0}
            max={100}
            step={0.1}
            suffix="%"
            className="w-full"
          />

          <NumberInputField
            label="Discount Amount"
            description="Fixed discount amount"
            value={data.pricing.discountAmount || ""}
            onChange={(e) =>
              handleNestedChange(
                "pricing",
                "discountAmount",
                e.target.value ? parseFloat(e.target.value) : undefined,
              )
            }
            min={0}
            step={0.01}
            prefix={currencySymbol}
            className="w-full"
          />
        </div>

        {/* Profit Calculation Display */}
        <div className="rounded-xl bg-muted/50 p-4 border border-border">
          <h4 className="text-sm font-medium text-foreground mb-3">
            Profit Calculation
          </h4>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
            <div className="space-y-1">
              <span className="text-muted-foreground">Purchase Price</span>
              <span className="font-medium text-foreground">
                {currencySymbol}
                {data.pricing.purchasePrice.toLocaleString()}
              </span>
            </div>
            <div className="space-y-1">
              <span className="text-muted-foreground">Selling Price</span>
              <span className="font-medium text-foreground">
                {currencySymbol}
                {data.pricing.sellingPrice.toLocaleString()}
              </span>
            </div>
            <div className="space-y-1">
              <span className="text-muted-foreground">Profit per Unit</span>
              <span className="font-medium text-green-600 dark:text-green-400">
                {currencySymbol}
                {profitPerUnit.toLocaleString()}
                {profitPerUnit > 0 && (
                  <span className="text-xs text-muted-foreground ml-2">
                    ({profitMargin}% margin)
                  </span>
                )}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* Inventory Section */}
      <section className="space-y-6 pt-6 border-t border-border">
        <header>
          <h3 className="text-lg font-semibold text-foreground">Inventory</h3>
          <p className="text-sm text-muted-foreground mt-1">
            Manage stock levels, thresholds, and physical properties
          </p>
        </header>

        <InputField
          label="SKU"
          description="Stock keeping unit (same as basic info SKU)"
          value={data.inventory.sku}
          onChange={(e) =>
            handleNestedChange("inventory", "sku", e.target.value.toUpperCase())
          }
          error={errors.inventory as string}
          placeholder="Auto-filled from basic info"
          className="w-full max-w-xs"
        />

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <NumberInputField
            label="Stock Quantity"
            description="Current available stock"
            error={errors.inventory as string}
            required
            value={data.inventory.stockQuantity}
            onChange={(e) =>
              handleNestedChange(
                "inventory",
                "stockQuantity",
                parseInt(e.target.value) || 0,
              )
            }
            min={0}
            step={1}
            className="w-full"
          />

          <NumberInputField
            label="Low Stock Threshold"
            description="Alert when stock falls below this level"
            value={data.inventory.lowStockThreshold}
            onChange={(e) =>
              handleNestedChange(
                "inventory",
                "lowStockThreshold",
                parseInt(e.target.value) || 10,
              )
            }
            min={0}
            step={1}
            className="w-full"
          />

          <FormField
            label="Stock Status"
            description="Current stock availability status"
          >
            <Select
              items={[
                { value: "in-stock", label: "In Stock" },
                { value: "low-stock", label: "Low Stock" },
                { value: "out-of-stock", label: "Out of Stock" },
                { value: "pre-order", label: "Pre-Order" },
                { value: "discontinued", label: "Discontinued" },
              ]}
              value={data.inventory.stockStatus}
              onValueChange={(v) =>
                handleNestedChange(
                  "inventory",
                  "stockStatus",
                  v as ProductFormData["inventory"]["stockStatus"],
                )
              }
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="in-stock">In Stock</SelectItem>
                <SelectItem value="low-stock">Low Stock</SelectItem>
                <SelectItem value="out-of-stock">Out of Stock</SelectItem>
                <SelectItem value="pre-order">Pre-Order</SelectItem>
                <SelectItem value="discontinued">Discontinued</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
        </div>

        {/* Physical Properties */}
        <div className="pt-6 border-t border-border">
          <h4 className="text-md font-medium text-foreground mb-4">
            Physical Properties (Optional)
          </h4>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <NumberInputField
              label="Weight (grams)"
              description="Product weight for shipping calculations"
              value={data.inventory.weight || ""}
              onChange={(e) =>
                handleNestedChange(
                  "inventory",
                  "weight",
                  e.target.value ? parseFloat(e.target.value) : undefined,
                )
              }
              min={0}
              step={1}
              suffix="g"
              className="w-full"
            />

            <div className="grid grid-cols-3 gap-2">
              <NumberInputField
                label="Length (cm)"
                description="Product length"
                value={data.inventory.dimensions?.length || ""}
                onChange={(e) =>
                  handleNestedChange("inventory", "dimensions", {
                    ...data.inventory.dimensions,
                    length: e.target.value
                      ? parseFloat(e.target.value)
                      : undefined,
                  })
                }
                min={0}
                step={0.1}
                className="w-full"
              />
              <NumberInputField
                label="Width (cm)"
                description="Product width"
                value={data.inventory.dimensions?.width || ""}
                onChange={(e) =>
                  handleNestedChange("inventory", "dimensions", {
                    ...data.inventory.dimensions,
                    width: e.target.value
                      ? parseFloat(e.target.value)
                      : undefined,
                  })
                }
                min={0}
                step={0.1}
                className="w-full"
              />
              <NumberInputField
                label="Height (cm)"
                description="Product height"
                value={data.inventory.dimensions?.height || ""}
                onChange={(e) =>
                  handleNestedChange("inventory", "dimensions", {
                    ...data.inventory.dimensions,
                    height: e.target.value
                      ? parseFloat(e.target.value)
                      : undefined,
                  })
                }
                min={0}
                step={0.1}
                className="w-full"
              />
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
