import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { Save, ArrowLeft, Upload, X, Plus, Trash2 } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";

type UnitRow = {
  unit_name: string;
  unit_name_bn: string;
  conversion_factor: string;
  retail_price: string;
  wholesale_price: string;
  purchase_price: string;
  barcode: string;
};

const emptyUnit = (): UnitRow => ({
  unit_name: "",
  unit_name_bn: "",
  conversion_factor: "",
  retail_price: "",
  wholesale_price: "",
  purchase_price: "",
  barcode: "",
});

export const Route = createFileRoute("/_authenticated/products/add")({
  head: () => ({
    meta: [
      { title: "নতুন পণ্য যোগ — Niyamah ERP" },
      { name: "description", content: "নতুন পণ্য যোগ করুন" },
    ],
  }),
  component: AddProductPage,
});

type CategoryRow = { id: string; name: string; name_bn: string };
type SubcategoryRow = { id: string; name: string; name_bn: string; category_id: string };
type BrandRow = { id: string; name: string };
type BranchRow = { id: string; name: string };
type GodownRow = { id: string; name: string; branch_id: string | null };

const UNITS = ["pcs", "box", "meter", "kg", "liter", "কয়েল", "সেট", "বস্তা"];
function AddProductPage() {
  const { tr, lang } = useLanguage();
  const navigate = useNavigate();
  const { user } = useAuth();
  const [saving, setSaving] = useState(false);
  const [categories, setCategories] = useState<CategoryRow[]>([]);
  const [subcategories, setSubcategories] = useState<SubcategoryRow[]>([]);
  const [brands, setBrands] = useState<BrandRow[]>([]);
  const [branches, setBranches] = useState<BranchRow[]>([]);
  const [godowns, setGodowns] = useState<GodownRow[]>([]);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [unitRows, setUnitRows] = useState<UnitRow[]>([]);

  const updateUnit = (idx: number, key: keyof UnitRow, val: string) => {
    setUnitRows((prev) => prev.map((r, i) => (i === idx ? { ...r, [key]: val } : r)));
  };
  const addUnitRow = () => setUnitRows((prev) => [...prev, emptyUnit()]);
  const removeUnitRow = (idx: number) => setUnitRows((prev) => prev.filter((_, i) => i !== idx));



  const [form, setForm] = useState({
    name: "",
    name_bn: "",
    sku: "",
    barcode: "",
    category_id: "",
    subcategory_id: "",
    brand_id: "",
    branch_id: "",
    godown_id: "",
    purchase_price: "",
    retail_price: "",
    wholesale_price: "",
    stock_quantity: "",
    unit: "pcs",
    product_type: "electric" as "electric" | "hardware",
  });

  useEffect(() => {
    supabase.from("categories").select("*").order("name_bn").then(({ data }) => {
      setCategories((data as CategoryRow[]) || []);
    });
    supabase.from("subcategories").select("*").order("name_bn").then(({ data }) => {
      setSubcategories((data as SubcategoryRow[]) || []);
    });
    supabase.from("brands").select("id, name").is("deleted_at", null).eq("status", "active").order("name").then(({ data }) => {
      setBrands((data as BrandRow[]) || []);
    });
    supabase.from("branches").select("id, name").is("deleted_at", null).eq("status", "active").order("name").then(({ data }) => {
      setBranches((data as BranchRow[]) || []);
    });
    supabase.from("godowns").select("id, name, branch_id").eq("status", "active").order("name").then(({ data }) => {
      setGodowns((data as GodownRow[]) || []);
    });
  }, []);

  const filteredGodowns = form.branch_id
    ? godowns.filter((g) => g.branch_id === form.branch_id || !g.branch_id)
    : godowns;

  const filteredSubs = subcategories.filter((s) => s.category_id === form.category_id);

  const handleChange = (key: string, val: string) => {
    setForm((prev) => ({ ...prev, [key]: val }));
    if (key === "category_id") setForm((prev) => ({ ...prev, [key]: val, subcategory_id: "" }));
    if (key === "branch_id") setForm((prev) => ({ ...prev, [key]: val, godown_id: "" }));
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
    const MAX_SIZE = 5 * 1024 * 1024;
    if (!ALLOWED_TYPES.includes(file.type)) {
      toast.error("Only JPG, PNG, WebP, and GIF images are allowed");
      return;
    }
    if (file.size > MAX_SIZE) {
      toast.error("Image must be less than 5 MB");
      return;
    }
    setImageFile(file);
    setImagePreview(URL.createObjectURL(file));
  };

  const generateSKU = () => {
    const prefix = form.name.slice(0, 3).toUpperCase() || "PRD";
    const rand = Math.floor(1000 + Math.random() * 9000);
    handleChange("sku", `${prefix}-${rand}`);
  };

  const generateBarcode = () => {
    const barcode = String(Math.floor(1000000000 + Math.random() * 9000000000));
    handleChange("barcode", barcode);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name || !form.sku) {
      toast.error(tr("skuRequired"));
      return;
    }
    setSaving(true);

    let image_url = "";
    if (imageFile) {
      const ext = imageFile.name.split(".").pop();
      const path = `${Date.now()}-${form.sku}.${ext}`;
      const { error: upErr } = await supabase.storage.from("product-images").upload(path, imageFile);
      if (upErr) { toast.error(tr("imageUploadFailed")); setSaving(false); return; }
      const { data: urlData } = supabase.storage.from("product-images").getPublicUrl(path);
      image_url = urlData.publicUrl;
    }

    const { data: inserted, error } = await supabase.from("products").insert({
      name: form.name,
      name_bn: form.name_bn,
      sku: form.sku,
      barcode: form.barcode || null,
      category_id: form.category_id || null,
      subcategory_id: form.subcategory_id || null,
      brand_id: form.brand_id || null,
      branch_id: form.branch_id || null,
      godown_id: form.godown_id || null,
      purchase_price: Number(form.purchase_price) || 0,
      retail_price: Number(form.retail_price) || 0,
      wholesale_price: Number(form.wholesale_price) || 0,
      stock_quantity: Number(form.stock_quantity) || 0,
      unit: form.unit,
      product_type: form.product_type,
      image_url,
      created_by: user?.id || null,
    }).select("id").single();

    if (error) {
      if (error.code === "23505") toast.error(tr("skuExists"));
      else { console.error("Product add error:", error); toast.error(tr("productAddFailed")); }
      setSaving(false);
      return;
    }
    // Save multi-unit rows
    const validUnits = unitRows.filter((u) => u.unit_name.trim() && Number(u.conversion_factor) > 0);
    if (validUnits.length > 0 && inserted?.id) {
      const payload = validUnits.map((u) => ({
        product_id: inserted.id,
        unit_name: u.unit_name.trim(),
        unit_name_bn: u.unit_name_bn.trim() || u.unit_name.trim(),
        conversion_factor: Number(u.conversion_factor),
        price: Number(u.retail_price) || 0,
        retail_price: Number(u.retail_price) || 0,
        wholesale_price: Number(u.wholesale_price) || 0,
        purchase_price: Number(u.purchase_price) || 0,
        barcode: u.barcode.trim() || null,
      }));
      const { error: unitErr } = await supabase.from("product_units").insert(payload);
      if (unitErr) console.error("Unit insert error:", unitErr);
    }

    // Save opening stock into godown_stocks if godown chosen
    const openingQty = Number(form.stock_quantity) || 0;
    if (inserted?.id && form.godown_id && openingQty > 0) {
      const { error: gsErr } = await supabase.from("godown_stocks").insert({
        godown_id: form.godown_id,
        product_id: inserted.id,
        quantity: openingQty,
      });
      if (gsErr) console.error("Godown stock insert error:", gsErr);
    }

    toast.success(lang === "bn" ? "পণ্য সফলভাবে যোগ হয়েছে" : "Product added successfully");
    navigate({ to: "/products" });
  };

  const inputClass = "w-full rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring";
  const labelClass = "block text-sm font-medium text-foreground mb-1";

  return (
    <PageLayout>
      <div className="mb-6 flex items-center gap-3">
        <button onClick={() => navigate({ to: "/products" })} className="rounded-lg p-2 text-muted-foreground hover:bg-secondary">
          <ArrowLeft className="h-5 w-5" />
        </button>
        <div>
          <h1 className="text-xl font-bold text-foreground">{tr("addProduct")}</h1>
          <p className="text-sm text-muted-foreground">{tr("fillProductInfo")}</p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Info */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">{tr("basicInfo")}</h2>
          <div className="mb-4">
            <label className={labelClass}>{tr("productType")} *</label>
            <div className="flex gap-3">
              <button type="button" onClick={() => handleChange("product_type", "electric")} className={`flex items-center gap-2 rounded-lg border-2 px-4 py-2.5 text-sm font-medium transition ${form.product_type === "electric" ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:border-primary/50"}`}>
                ⚡ Electric
              </button>
              <button type="button" onClick={() => handleChange("product_type", "hardware")} className={`flex items-center gap-2 rounded-lg border-2 px-4 py-2.5 text-sm font-medium transition ${form.product_type === "hardware" ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:border-primary/50"}`}>
                🔩 Hardware
              </button>
            </div>
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <label className={labelClass}>{tr("productNameEn")} *</label>
              <input className={inputClass} value={form.name} onChange={(e) => handleChange("name", e.target.value)} placeholder="e.g. BRB Wire 1.3mm" required />
            </div>
            <div>
              <label className={labelClass}>{tr("productNameBn")}</label>
              <input className={inputClass} value={form.name_bn} onChange={(e) => handleChange("name_bn", e.target.value)} placeholder="যেমন: বিআরবি তার ১.৩মিমি" />
            </div>
            <div>
              <label className={labelClass}>{tr("categoryLabel")}</label>
              <select className={inputClass} value={form.category_id} onChange={(e) => handleChange("category_id", e.target.value)}>
                <option value="">{tr("selectOption")}</option>
                {categories.map((c) => (
                  <option key={c.id} value={c.id}>{lang === "bn" ? c.name_bn : c.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className={labelClass}>{tr("subcategoryLabel")}</label>
              <select className={inputClass} value={form.subcategory_id} onChange={(e) => handleChange("subcategory_id", e.target.value)} disabled={!form.category_id}>
                <option value="">{tr("selectOption")}</option>
                {filteredSubs.map((s) => (
                  <option key={s.id} value={s.id}>{lang === "bn" ? s.name_bn : s.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className={labelClass}>{tr("brands")}</label>
              <select className={inputClass} value={form.brand_id} onChange={(e) => handleChange("brand_id", e.target.value)}>
                <option value="">{tr("selectOption")}</option>
                {brands.map((b) => (<option key={b.id} value={b.id}>{b.name}</option>))}
              </select>
            </div>
            <div>
              <label className={labelClass}>{tr("branches")}</label>
              <select className={inputClass} value={form.branch_id} onChange={(e) => handleChange("branch_id", e.target.value)}>
                <option value="">{tr("selectOption")}</option>
                {branches.map((b) => (<option key={b.id} value={b.id}>{b.name}</option>))}
              </select>
            </div>
            <div>
              <label className={labelClass}>{lang === "bn" ? "গুদাম / ওয়্যারহাউস" : "Godown / Warehouse"}</label>
              <select className={inputClass} value={form.godown_id} onChange={(e) => handleChange("godown_id", e.target.value)}>
                <option value="">{tr("selectOption")}</option>
                {filteredGodowns.map((g) => (<option key={g.id} value={g.id}>{g.name}</option>))}
              </select>
              {form.branch_id && filteredGodowns.length === 0 && (
                <p className="mt-1 text-xs text-amber-600">{lang === "bn" ? "এই শাখায় কোনো গুদাম নেই" : "No godowns for this branch"}</p>
              )}
            </div>
          </div>
        </div>

        {/* SKU & Barcode */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">{tr("skuBarcode")}</h2>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <label className={labelClass}>{tr("skuLabel")} *</label>
              <div className="flex gap-2">
                <input className={inputClass} value={form.sku} onChange={(e) => handleChange("sku", e.target.value)} placeholder="PRD-1234" required />
                <button type="button" onClick={generateSKU} className="shrink-0 rounded-lg bg-secondary px-3 py-2 text-xs font-medium text-secondary-foreground hover:bg-secondary/80">
                  Auto
                </button>
              </div>
            </div>
            <div>
              <label className={labelClass}>{tr("barcodeLabel")}</label>
              <div className="flex gap-2">
                <input className={inputClass} value={form.barcode} onChange={(e) => handleChange("barcode", e.target.value)} placeholder="1234567890" />
                <button type="button" onClick={generateBarcode} className="shrink-0 rounded-lg bg-secondary px-3 py-2 text-xs font-medium text-secondary-foreground hover:bg-secondary/80">
                  Auto
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Base Pricing */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">{tr("pricingSection")}</h2>
          <div className="grid gap-4 md:grid-cols-3">
            <div>
              <label className={labelClass}>{tr("purchasePrice")}</label>
              <input type="number" className={inputClass} value={form.purchase_price} onChange={(e) => handleChange("purchase_price", e.target.value)} placeholder="0" min="0" step="0.01" />
            </div>
            <div>
              <label className={labelClass}>{tr("retailPrice")}</label>
              <input type="number" className={inputClass} value={form.retail_price} onChange={(e) => handleChange("retail_price", e.target.value)} placeholder="0" min="0" step="0.01" />
            </div>
            <div>
              <label className={labelClass}>{tr("wholesalePrice")}</label>
              <input type="number" className={inputClass} value={form.wholesale_price} onChange={(e) => handleChange("wholesale_price", e.target.value)} placeholder="0" min="0" step="0.01" />
            </div>
          </div>
        </div>

        {/* Stock & Unit */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">{tr("stockUnit")}</h2>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <label className={labelClass}>{tr("openingStock")}</label>
              <input type="number" className={inputClass} value={form.stock_quantity} onChange={(e) => handleChange("stock_quantity", e.target.value)} placeholder="0" min="0" />
            </div>
            <div>
              <label className={labelClass}>{tr("unitLabel")}</label>
              <select className={inputClass} value={form.unit} onChange={(e) => handleChange("unit", e.target.value)}>
                {UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
              </select>
            </div>
          </div>
        </div>

        {/* Multi Unit */}
        <div className="rounded-xl border border-border bg-card p-5">
          <div className="mb-4 flex items-center justify-between">
            <div>
              <h2 className="text-sm font-semibold text-foreground">{tr("multiUnit")}</h2>
              <p className="text-xs text-muted-foreground mt-0.5">{tr("baseUnit")} = {form.unit} · {tr("conversionHint")}</p>
            </div>
            <button type="button" onClick={addUnitRow} className="flex items-center gap-1 rounded-lg bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20">
              <Plus className="h-3.5 w-3.5" /> {tr("addUnitRow")}
            </button>
          </div>
          {unitRows.length === 0 ? (
            <p className="text-xs text-muted-foreground italic">{lang === "bn" ? "কোনো অতিরিক্ত ইউনিট নেই (যেমন: Box, Carton)" : "No additional units (e.g. Box, Carton)"}</p>
          ) : (
            <div className="space-y-3">
              {unitRows.map((u, idx) => (
                <div key={idx} className="grid grid-cols-12 gap-2 items-end rounded-lg border border-border/60 bg-background p-3">
                  <div className="col-span-12 md:col-span-2">
                    <label className="text-[11px] text-muted-foreground">{tr("unitNameEn")}</label>
                    <input className={inputClass} placeholder="Box" value={u.unit_name} onChange={(e) => updateUnit(idx, "unit_name", e.target.value)} />
                  </div>
                  <div className="col-span-12 md:col-span-2">
                    <label className="text-[11px] text-muted-foreground">{tr("unitNameBn")}</label>
                    <input className={inputClass} placeholder="বক্স" value={u.unit_name_bn} onChange={(e) => updateUnit(idx, "unit_name_bn", e.target.value)} />
                  </div>
                  <div className="col-span-6 md:col-span-2">
                    <label className="text-[11px] text-muted-foreground">{tr("conversionFactor")}</label>
                    <input type="number" min="1" step="0.01" className={inputClass} placeholder="12" value={u.conversion_factor} onChange={(e) => updateUnit(idx, "conversion_factor", e.target.value)} />
                  </div>
                  <div className="col-span-6 md:col-span-2">
                    <label className="text-[11px] text-muted-foreground">🛒 Retail Price</label>
                    <input type="number" min="0" step="0.01" className={inputClass} placeholder="0" value={u.retail_price} onChange={(e) => updateUnit(idx, "retail_price", e.target.value)} />
                  </div>
                  <div className="col-span-6 md:col-span-1">
                    <label className="text-[11px] text-muted-foreground">🏪 Wholesale</label>
                    <input type="number" min="0" step="0.01" className={inputClass} placeholder="0" value={u.wholesale_price} onChange={(e) => updateUnit(idx, "wholesale_price", e.target.value)} />
                  </div>
                  <div className="col-span-6 md:col-span-1">
                    <label className="text-[11px] text-muted-foreground">{tr("unitPurchasePrice")}</label>
                    <input type="number" min="0" step="0.01" className={inputClass} placeholder="0" value={u.purchase_price} onChange={(e) => updateUnit(idx, "purchase_price", e.target.value)} />
                  </div>
                  <div className="col-span-5 md:col-span-1">
                    <label className="text-[11px] text-muted-foreground">{tr("barcodeLabel")}</label>
                    <input className={inputClass} placeholder="—" value={u.barcode} onChange={(e) => updateUnit(idx, "barcode", e.target.value)} />
                  </div>
                  <div className="col-span-1 flex justify-end">
                    <button type="button" onClick={() => removeUnitRow(idx)} className="rounded-md p-2 text-destructive hover:bg-destructive/10">
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Image */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">{tr("productImage")}</h2>
          <div className="flex items-start gap-4">
            {imagePreview ? (
              <div className="relative">
                <img src={imagePreview} alt="preview" className="h-24 w-24 rounded-lg object-cover border border-border" />
                <button type="button" onClick={() => { setImageFile(null); setImagePreview(null); }} className="absolute -top-2 -right-2 rounded-full bg-destructive p-0.5 text-destructive-foreground">
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            ) : (
              <label className="flex h-24 w-24 cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-border text-muted-foreground hover:border-primary hover:text-primary transition">
                <Upload className="h-5 w-5" />
                <span className="text-[10px] mt-1">{tr("uploadLabel")}</span>
                <input type="file" accept="image/*" className="hidden" onChange={handleImageChange} />
              </label>
            )}
          </div>
        </div>

        {/* Submit */}
        <div className="flex gap-3">
          <button type="submit" disabled={saving} className="flex items-center gap-2 rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground transition hover:bg-primary/90 disabled:opacity-50">
            <Save className="h-4 w-4" />
            {saving ? tr("saving") : tr("saveProduct")}
          </button>
          <button type="button" onClick={() => navigate({ to: "/products" })} className="rounded-lg border border-border px-6 py-2.5 text-sm font-medium text-muted-foreground hover:bg-secondary">
            {tr("cancel")}
          </button>
        </div>
      </form>
    </PageLayout>
  );
}
