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, PackageMinus, PackagePlus } from "lucide-react";

export const Route = createFileRoute("/_authenticated/products/$productId/edit")({
  head: () => ({
    meta: [
      { title: "পণ্য সম্পাদনা — Niyamah ERP" },
      { name: "description", content: "পণ্য সম্পাদনা করুন" },
    ],
  }),
  component: EditProductPage,
});

type CategoryRow = { id: string; name: string; name_bn: string };
type SubcategoryRow = { id: string; name: string; name_bn: string; category_id: 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 EditProductPage() {
  const { lang } = useLanguage();
  const navigate = useNavigate();
  const { productId } = Route.useParams();
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [categories, setCategories] = useState<CategoryRow[]>([]);
  const [subcategories, setSubcategories] = useState<SubcategoryRow[]>([]);
  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 [stockAdjust, setStockAdjust] = useState({ qty: "", reason: "" });
  const [showStockAdjust, setShowStockAdjust] = useState(false);

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

  useEffect(() => {
    const load = async () => {
      const [{ data: product }, { data: cats }, { data: subs }, { data: brs }, { data: gds }] = await Promise.all([
        supabase.from("products").select("*").eq("id", productId).single(),
        supabase.from("categories").select("*").order("name_bn"),
        supabase.from("subcategories").select("*").order("name_bn"),
        supabase.from("branches").select("id, name").is("deleted_at", null).eq("status", "active").order("name"),
        supabase.from("godowns").select("id, name, branch_id").eq("status", "active").order("name"),
      ]);
      if (!product) { toast.error("পণ্য পাওয়া যায়নি"); navigate({ to: "/products" }); return; }
      setCategories((cats as CategoryRow[]) || []);
      setSubcategories((subs as SubcategoryRow[]) || []);
      setBranches((brs as BranchRow[]) || []);
      setGodowns((gds as GodownRow[]) || []);
      setForm({
        name: product.name, name_bn: product.name_bn,
        sku: product.sku, barcode: product.barcode || "",
        category_id: product.category_id || "", subcategory_id: product.subcategory_id || "",
        branch_id: (product as any).branch_id || "", godown_id: (product as any).godown_id || "",
        purchase_price: String(product.purchase_price),
        retail_price: String(product.retail_price),
        wholesale_price: String(product.wholesale_price),
        stock_quantity: Number(product.stock_quantity), unit: product.unit,
        image_url: product.image_url || "",
        product_type: (product.product_type as "electric" | "hardware") || "electric",
      });
      if (product.image_url) setImagePreview(product.image_url);
      setLoading(false);
    };
    load();
  }, [productId]);

  const filteredSubs = subcategories.filter((s) => s.category_id === form.category_id);
  const filteredGodowns = form.branch_id
    ? godowns.filter((g) => g.branch_id === form.branch_id || !g.branch_id)
    : godowns;
  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; // 5 MB
    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 handleStockAdjust = async (direction: "add" | "subtract") => {
    const qty = Number(stockAdjust.qty);
    if (!qty || qty <= 0) { toast.error("সঠিক পরিমাণ দিন"); return; }
    const change = direction === "add" ? qty : -qty;
    const newStock = form.stock_quantity + change;
    if (newStock < 0) { toast.error("স্টক নেগেটিভ হতে পারে না"); return; }

    const { error: adjErr } = await supabase.from("stock_adjustments").insert({
      product_id: productId, quantity_change: change, reason: stockAdjust.reason,
    });
    if (adjErr) { toast.error("স্টক অ্যাডজাস্ট ব্যর্থ"); return; }

    const { error } = await supabase.from("products").update({ stock_quantity: newStock }).eq("id", productId);
    if (error) { toast.error("স্টক আপডেট ব্যর্থ"); return; }

    setForm((prev) => ({ ...prev, stock_quantity: newStock }));
    setStockAdjust({ qty: "", reason: "" });
    toast.success(`স্টক ${direction === "add" ? "বৃদ্ধি" : "হ্রাস"} হয়েছে: ${qty}`);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name || !form.sku) { toast.error("Product Name ও SKU আবশ্যক"); return; }
    setSaving(true);

    let image_url = form.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("ছবি আপলোড ব্যর্থ"); setSaving(false); return; }
      const { data: urlData } = supabase.storage.from("product-images").getPublicUrl(path);
      image_url = urlData.publicUrl;
    }

    const { error } = await supabase.from("products").update({
      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,
      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,
      unit: form.unit, image_url, product_type: form.product_type,
    }).eq("id", productId);

    if (error) {
      if (error.code === "23505") toast.error("এই SKU ইতিমধ্যে ব্যবহৃত");
      else { console.error("Product update error:", error); toast.error("আপডেট ব্যর্থ হয়েছে"); }
      setSaving(false); return;
    }

    toast.success("পণ্য সফলভাবে আপডেট হয়েছে!");
    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";

  if (loading) return <PageLayout><div className="flex h-40 items-center justify-center text-muted-foreground">লোড হচ্ছে...</div></PageLayout>;

  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">পণ্য সম্পাদনা</h1>
          <p className="text-sm text-muted-foreground">{form.name} — {form.sku}</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">📋 মূল তথ্য</h2>
          <div className="mb-4">
            <label className={labelClass}>পণ্যের ধরন (Product Type) *</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}>Product Name (English) *</label>
              <input className={inputClass} value={form.name} onChange={(e) => handleChange("name", e.target.value)} required />
            </div>
            <div>
              <label className={labelClass}>পণ্যের নাম (বাংলা)</label>
              <input className={inputClass} value={form.name_bn} onChange={(e) => handleChange("name_bn", e.target.value)} />
            </div>
            <div>
              <label className={labelClass}>ক্যাটাগরি</label>
              <select className={inputClass} value={form.category_id} onChange={(e) => handleChange("category_id", e.target.value)}>
                <option value="">নির্বাচন করুন</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}>সাব-ক্যাটাগরি</label>
              <select className={inputClass} value={form.subcategory_id} onChange={(e) => handleChange("subcategory_id", e.target.value)} disabled={!form.category_id}>
                <option value="">নির্বাচন করুন</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}>{lang === "bn" ? "শাখা" : "Branch"}</label>
              <select className={inputClass} value={form.branch_id} onChange={(e) => handleChange("branch_id", e.target.value)}>
                <option value="">{lang === "bn" ? "নির্বাচন করুন" : "Select"}</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="">{lang === "bn" ? "নির্বাচন করুন" : "Select"}</option>
                {filteredGodowns.map((g) => <option key={g.id} value={g.id}>{g.name}</option>)}
              </select>
            </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">🔖 SKU ও বারকোড</h2>
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <label className={labelClass}>SKU *</label>
              <input className={inputClass} value={form.sku} onChange={(e) => handleChange("sku", e.target.value)} required />
            </div>
            <div>
              <label className={labelClass}>বারকোড</label>
              <input className={inputClass} value={form.barcode} onChange={(e) => handleChange("barcode", e.target.value)} />
            </div>
          </div>
        </div>

        {/* Pricing */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">💰 মূল্য নির্ধারণ</h2>
          <div className="grid gap-4 md:grid-cols-3">
            <div>
              <label className={labelClass}>ক্রয় মূল্য (৳)</label>
              <input type="number" className={inputClass} value={form.purchase_price} onChange={(e) => handleChange("purchase_price", e.target.value)} min="0" step="0.01" />
            </div>
            <div>
              <label className={labelClass}>খুচরা মূল্য (৳)</label>
              <input type="number" className={inputClass} value={form.retail_price} onChange={(e) => handleChange("retail_price", e.target.value)} min="0" step="0.01" />
            </div>
            <div>
              <label className={labelClass}>পাইকারি মূল্য (৳)</label>
              <input type="number" className={inputClass} value={form.wholesale_price} onChange={(e) => handleChange("wholesale_price", e.target.value)} min="0" step="0.01" />
            </div>
          </div>
        </div>

        {/* Stock */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">📦 স্টক ম্যানেজমেন্ট</h2>
          <div className="mb-3 flex items-center gap-4">
            <span className="text-sm text-muted-foreground">বর্তমান স্টক:</span>
            <span className="text-lg font-bold text-foreground">{form.stock_quantity} {form.unit}</span>
            <button type="button" onClick={() => setShowStockAdjust(!showStockAdjust)} className="rounded-lg bg-secondary px-3 py-1.5 text-xs font-medium text-secondary-foreground hover:bg-secondary/80">
              স্টক অ্যাডজাস্ট
            </button>
          </div>
          {showStockAdjust && (
            <div className="mt-3 rounded-lg border border-border bg-muted/30 p-4">
              <div className="grid gap-3 md:grid-cols-3">
                <input type="number" className={inputClass} value={stockAdjust.qty} onChange={(e) => setStockAdjust((p) => ({ ...p, qty: e.target.value }))} placeholder="পরিমাণ" min="1" />
                <input className={inputClass} value={stockAdjust.reason} onChange={(e) => setStockAdjust((p) => ({ ...p, reason: e.target.value }))} placeholder="কারণ (ঐচ্ছিক)" />
                <div className="flex gap-2">
                  <button type="button" onClick={() => handleStockAdjust("add")} className="flex items-center gap-1 rounded-lg bg-green-600 px-3 py-2 text-xs font-medium text-white hover:bg-green-700">
                    <PackagePlus className="h-3.5 w-3.5" /> বৃদ্ধি
                  </button>
                  <button type="button" onClick={() => handleStockAdjust("subtract")} className="flex items-center gap-1 rounded-lg bg-destructive px-3 py-2 text-xs font-medium text-destructive-foreground hover:bg-destructive/90">
                    <PackageMinus className="h-3.5 w-3.5" /> হ্রাস
                  </button>
                </div>
              </div>
            </div>
          )}
          <div className="mt-4">
            <label className={labelClass}>ইউনিট</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>

        {/* Image */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="mb-4 text-sm font-semibold text-foreground">🖼️ পণ্যের ছবি</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); setForm((p) => ({ ...p, image_url: "" })); }} 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">আপলোড</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 ? "আপডেট হচ্ছে..." : "আপডেট করুন"}
          </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">
            বাতিল
          </button>
        </div>
      </form>
    </PageLayout>
  );
}
