import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useState, useEffect, useRef } from "react";
import { useAuth } from "@/hooks/use-auth";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Loader2, Search, RotateCcw, RefreshCw, AlertTriangle, Banknote } from "lucide-react";

export const Route = createFileRoute("/_authenticated/returns")({
  head: () => ({
    meta: [
      { title: "রিটার্ন ও রিফান্ড — Niyamah ERP" },
      { name: "description", content: "বিক্রয় রিটার্ন, রিপ্লেসমেন্ট ও রিফান্ড ম্যানেজমেন্ট" },
    ],
  }),
  component: ReturnsPage,
});

type ReturnType = "fresh" | "replacement" | "normal";

function ReturnsPage() {
  const { tr, lang } = useLanguage();
  const { user } = useAuth();
  const queryClient = useQueryClient();

  // Form state
  const [returnType, setReturnType] = useState<ReturnType>("normal");
  const [invoiceId, setInvoiceId] = useState("");
  const [reason, setReason] = useState("");
  const [quantity, setQuantity] = useState(1);
  const [wantRefund, setWantRefund] = useState(false);
  const [refundAmount, setRefundAmount] = useState(0);
  const [refundMethod, setRefundMethod] = useState("cash");

  // Customer search
  const [customerQuery, setCustQuery] = useState("");
  const [customerResults, setCustResults] = useState<any[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<any>(null);
  const [showCustDrop, setShowCustDrop] = useState(false);
  const custRef = useRef<HTMLDivElement>(null);

  // Product search
  const [prodQuery, setProdQuery] = useState("");
  const [prodResults, setProdResults] = useState<any[]>([]);
  const [selectedProduct, setSelectedProduct] = useState<any>(null);
  const [showProdDrop, setShowProdDrop] = useState(false);
  const prodRef = useRef<HTMLDivElement>(null);

  // Replacement product search
  const [replQuery, setReplQuery] = useState("");
  const [replResults, setReplResults] = useState<any[]>([]);
  const [selectedReplacement, setSelectedReplacement] = useState<any>(null);
  const [showReplDrop, setShowReplDrop] = useState(false);
  const replRef = useRef<HTMLDivElement>(null);

  // Fetch returns list
  const { data: returns, isLoading } = useQuery({
    queryKey: ["sales_returns"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("sales_returns")
        .select("*")
        .order("created_at", { ascending: false })
        .limit(50);
      if (error) throw error;
      return data;
    },
  });

  // Debounced search for customers
  useEffect(() => {
    if (customerQuery.length < 2) { setCustResults([]); return; }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("customers")
        .select("id, name, name_bn, mobile")
        .or(`name.ilike.%${customerQuery}%,name_bn.ilike.%${customerQuery}%,mobile.ilike.%${customerQuery}%`)
        .eq("status", "active")
        .limit(5);
      setCustResults(data || []);
      setShowCustDrop(true);
    }, 300);
    return () => clearTimeout(t);
  }, [customerQuery]);

  // Debounced search for products
  useEffect(() => {
    if (prodQuery.length < 2) { setProdResults([]); return; }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("products")
        .select("id, name, name_bn, sku, stock_quantity, retail_price")
        .or(`name.ilike.%${prodQuery}%,name_bn.ilike.%${prodQuery}%,sku.ilike.%${prodQuery}%`)
        .eq("is_deleted", false)
        .limit(5);
      setProdResults(data || []);
      setShowProdDrop(true);
    }, 300);
    return () => clearTimeout(t);
  }, [prodQuery]);

  // Debounced search for replacement product
  useEffect(() => {
    if (replQuery.length < 2) { setReplResults([]); return; }
    const t = setTimeout(async () => {
      const { data } = await supabase
        .from("products")
        .select("id, name, name_bn, sku, stock_quantity, retail_price")
        .or(`name.ilike.%${replQuery}%,name_bn.ilike.%${replQuery}%,sku.ilike.%${replQuery}%`)
        .eq("is_deleted", false)
        .limit(5);
      setReplResults(data || []);
      setShowReplDrop(true);
    }, 300);
    return () => clearTimeout(t);
  }, [replQuery]);

  // Close dropdowns on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (custRef.current && !custRef.current.contains(e.target as Node)) setShowCustDrop(false);
      if (prodRef.current && !prodRef.current.contains(e.target as Node)) setShowProdDrop(false);
      if (replRef.current && !replRef.current.contains(e.target as Node)) setShowReplDrop(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  // Submit mutation
  const submitReturn = useMutation({
    mutationFn: async () => {
      if (!selectedProduct) throw new Error("Product required");
      if (returnType === "replacement" && !selectedReplacement) throw new Error("Replacement product required");

      // 1. Insert sales_return
      const { data: returnData, error: returnErr } = await supabase
        .from("sales_returns")
        .insert({
          invoice_id: invoiceId,
          customer_id: selectedCustomer?.id || null,
          product_id: selectedProduct.id,
          quantity,
          return_type: returnType,
          replacement_product_id: returnType === "replacement" ? selectedReplacement.id : null,
          refund_amount: wantRefund ? refundAmount : 0,
          reason,
          status: "completed",
          processed_by: user?.id,
        })
        .select()
        .single();
      if (returnErr) throw returnErr;

      // 2. Stock adjustments based on return type
      if (returnType === "fresh") {
        // Fresh return: add back to main stock
        await supabase.from("stock_adjustments").insert({
          product_id: selectedProduct.id,
          quantity_change: quantity,
          reason: `Fresh return - Invoice: ${invoiceId}`,
          adjusted_by: user?.id,
        });
        // Update product stock
        await supabase.from("products").update({
          stock_quantity: selectedProduct.stock_quantity + quantity,
        }).eq("id", selectedProduct.id);
      } else if (returnType === "normal") {
        // Normal/Damage return: add to damage stock
        await supabase.from("damage_stock").insert({
          product_id: selectedProduct.id,
          quantity,
          source: "return",
          reference_id: returnData.id,
          note: reason,
        });
      } else if (returnType === "replacement") {
        // Old product → damage stock
        await supabase.from("damage_stock").insert({
          product_id: selectedProduct.id,
          quantity,
          source: "replacement",
          reference_id: returnData.id,
          note: `Replaced with ${selectedReplacement.name}`,
        });
        // New product → main stock decrease
        await supabase.from("stock_adjustments").insert({
          product_id: selectedReplacement.id,
          quantity_change: -quantity,
          reason: `Replacement for return - Invoice: ${invoiceId}`,
          adjusted_by: user?.id,
        });
        await supabase.from("products").update({
          stock_quantity: selectedReplacement.stock_quantity - quantity,
        }).eq("id", selectedReplacement.id);
      }

      // 3. Refund if requested
      if (wantRefund && refundAmount > 0 && selectedCustomer) {
        await supabase.from("refunds").insert({
          customer_id: selectedCustomer.id,
          return_id: returnData.id,
          amount: refundAmount,
          payment_method: refundMethod,
          status: "completed",
          processed_by: user?.id,
        });
        // Record customer transaction
        await supabase.from("customer_transactions").insert({
          customer_id: selectedCustomer.id,
          type: "refund",
          amount: refundAmount,
          method: refundMethod,
          reference_id: returnData.id,
          note: `Refund for return - ${reason}`,
        });
      }

      // 4. Activity log
      await supabase.from("activity_log").insert({
        user_id: user?.id!,
        action: "sales_return",
        entity_type: "sales_returns",
        entity_id: returnData.id,
        details: { return_type: returnType, product: selectedProduct.name, quantity, refund: wantRefund ? refundAmount : 0 },
      });
    },
    onSuccess: () => {
      toast.success(tr("returnSuccess"));
      queryClient.invalidateQueries({ queryKey: ["sales_returns"] });
      // Reset form
      setReturnType("normal");
      setInvoiceId("");
      setReason("");
      setQuantity(1);
      setWantRefund(false);
      setRefundAmount(0);
      setSelectedProduct(null);
      setSelectedCustomer(null);
      setSelectedReplacement(null);
      setProdQuery("");
      setCustQuery("");
      setReplQuery("");
    },
    onError: (err: any) => {
      toast.error(err.message || tr("somethingWrong"));
    },
  });

  const returnTypeOptions: { value: ReturnType; icon: React.ElementType; labelKey: string; descKey: string; color: string }[] = [
    { value: "fresh", icon: RefreshCw, labelKey: "freshReturn", descKey: "freshReturnDesc", color: "text-green-500 border-green-500 bg-green-500/10" },
    { value: "replacement", icon: RotateCcw, labelKey: "replacementReturn", descKey: "replacementReturnDesc", color: "text-blue-500 border-blue-500 bg-blue-500/10" },
    { value: "normal", icon: AlertTriangle, labelKey: "damageReturn", descKey: "damageReturnDesc", color: "text-red-500 border-red-500 bg-red-500/10" },
  ];

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("returnTitle")}</h1>
        <p className="text-sm text-muted-foreground">{tr("returnSubtitle")}</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Return Form */}
        <div className="lg:col-span-2 space-y-5">
          {/* Return Type Selection */}
          <div className="rounded-xl border border-border bg-card p-5">
            <h2 className="text-sm font-semibold text-foreground mb-3">{tr("selectReturnType")}</h2>
            <div className="grid grid-cols-3 gap-3">
              {returnTypeOptions.map((opt) => {
                const Icon = opt.icon;
                const selected = returnType === opt.value;
                return (
                  <button
                    key={opt.value}
                    onClick={() => setReturnType(opt.value)}
                    className={`rounded-lg border-2 p-3 text-left transition-all ${selected ? opt.color : "border-border bg-card hover:border-muted-foreground/30"}`}
                  >
                    <Icon className={`h-5 w-5 mb-1 ${selected ? "" : "text-muted-foreground"}`} />
                    <p className="text-xs font-semibold">{tr(opt.labelKey)}</p>
                    <p className="text-[10px] text-muted-foreground mt-0.5">{tr(opt.descKey)}</p>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Form Fields */}
          <div className="rounded-xl border border-border bg-card p-5 space-y-4">
            {/* Invoice ID */}
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("invoiceId")}</label>
              <input
                value={invoiceId}
                onChange={(e) => setInvoiceId(e.target.value)}
                className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                placeholder={tr("invoiceIdPlaceholder")}
              />
            </div>

            {/* Customer Search */}
            <div ref={custRef} className="relative">
              <label className="text-xs font-medium text-muted-foreground">{tr("customer")}</label>
              <div className="relative mt-1">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                <input
                  value={selectedCustomer ? `${selectedCustomer.name} (${selectedCustomer.mobile})` : customerQuery}
                  onChange={(e) => { setCustQuery(e.target.value); setSelectedCustomer(null); }}
                  className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder={tr("searchCustomer")}
                />
              </div>
              {showCustDrop && customerResults.length > 0 && (
                <div className="absolute z-20 mt-1 w-full rounded-lg border border-border bg-card shadow-lg max-h-40 overflow-y-auto">
                  {customerResults.map((c) => (
                    <button key={c.id} onClick={() => { setSelectedCustomer(c); setShowCustDrop(false); setCustQuery(""); }}
                      className="w-full px-3 py-2 text-left text-sm hover:bg-accent/50 flex justify-between">
                      <span>{lang === "bn" ? c.name_bn || c.name : c.name}</span>
                      <span className="text-xs text-muted-foreground">{c.mobile}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Return Product Search */}
            <div ref={prodRef} className="relative">
              <label className="text-xs font-medium text-muted-foreground">{tr("returnProduct")}</label>
              <div className="relative mt-1">
                <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                <input
                  value={selectedProduct ? `${selectedProduct.name} (${selectedProduct.sku})` : prodQuery}
                  onChange={(e) => { setProdQuery(e.target.value); setSelectedProduct(null); }}
                  className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder={tr("searchProductLabel")}
                />
              </div>
              {showProdDrop && prodResults.length > 0 && (
                <div className="absolute z-20 mt-1 w-full rounded-lg border border-border bg-card shadow-lg max-h-40 overflow-y-auto">
                  {prodResults.map((p) => (
                    <button key={p.id} onClick={() => { setSelectedProduct(p); setShowProdDrop(false); setProdQuery(""); }}
                      className="w-full px-3 py-2 text-left text-sm hover:bg-accent/50 flex justify-between">
                      <span>{lang === "bn" ? p.name_bn || p.name : p.name}</span>
                      <span className="text-xs text-muted-foreground">SKU: {p.sku} | ৳{p.retail_price}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Quantity */}
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("quantity")}</label>
              <input
                type="number"
                min={1}
                value={quantity}
                onChange={(e) => setQuantity(Number(e.target.value))}
                className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
              />
            </div>

            {/* Replacement Product (only for replacement type) */}
            {returnType === "replacement" && (
              <div ref={replRef} className="relative">
                <label className="text-xs font-medium text-muted-foreground">{tr("replacementProduct")}</label>
                <div className="relative mt-1">
                  <Search className="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />
                  <input
                    value={selectedReplacement ? `${selectedReplacement.name} (${selectedReplacement.sku})` : replQuery}
                    onChange={(e) => { setReplQuery(e.target.value); setSelectedReplacement(null); }}
                    className="w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                    placeholder={tr("searchReplacementProduct")}
                  />
                </div>
                {showReplDrop && replResults.length > 0 && (
                  <div className="absolute z-20 mt-1 w-full rounded-lg border border-border bg-card shadow-lg max-h-40 overflow-y-auto">
                    {replResults.map((p) => (
                      <button key={p.id} onClick={() => { setSelectedReplacement(p); setShowReplDrop(false); setReplQuery(""); }}
                        className="w-full px-3 py-2 text-left text-sm hover:bg-accent/50 flex justify-between">
                        <span>{lang === "bn" ? p.name_bn || p.name : p.name}</span>
                        <span className="text-xs text-muted-foreground">স্টক: {p.stock_quantity} | ৳{p.retail_price}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* Reason */}
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("returnReason")}</label>
              <textarea
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                rows={2}
                className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
                placeholder={tr("returnReasonPlaceholder")}
              />
            </div>

            {/* Refund Option */}
            <div className="rounded-lg border border-border p-3 space-y-3">
              <label className="flex items-center gap-2 cursor-pointer">
                <input type="checkbox" checked={wantRefund} onChange={(e) => setWantRefund(e.target.checked)}
                  className="h-4 w-4 rounded border-border" />
                <span className="text-sm font-medium">{tr("wantRefund")}</span>
              </label>
              {wantRefund && (
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs text-muted-foreground">{tr("refundAmount")}</label>
                    <input
                      type="number"
                      min={0}
                      value={refundAmount}
                      onChange={(e) => setRefundAmount(Number(e.target.value))}
                      className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground">{tr("refundMethod")}</label>
                    <select
                      value={refundMethod}
                      onChange={(e) => setRefundMethod(e.target.value)}
                      className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="cash">{tr("cash")}</option>
                      <option value="bank">{tr("bankTransfer")}</option>
                      <option value="mobile">{tr("bkash")}</option>
                    </select>
                  </div>
                </div>
              )}
            </div>

            {/* Submit */}
            <button
              disabled={submitReturn.isPending || !selectedProduct}
              onClick={() => submitReturn.mutate()}
              className="w-full rounded-lg bg-primary py-2.5 text-sm font-semibold text-primary-foreground hover:opacity-90 transition-opacity disabled:opacity-50"
            >
              {submitReturn.isPending ? <Loader2 className="h-4 w-4 animate-spin mx-auto" /> : tr("submitReturn")}
            </button>
          </div>
        </div>

        {/* Returns History */}
        <div className="rounded-xl border border-border bg-card p-5">
          <h2 className="text-sm font-semibold text-foreground mb-3">{tr("returnHistory")}</h2>
          {isLoading ? (
            <div className="flex justify-center py-8"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>
          ) : !returns?.length ? (
            <p className="text-xs text-muted-foreground text-center py-8">{tr("noReturns")}</p>
          ) : (
            <div className="space-y-2 max-h-[500px] overflow-y-auto">
              {returns.map((r) => (
                <div key={r.id} className="rounded-lg border border-border p-3 space-y-1">
                  <div className="flex items-center justify-between">
                    <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-full ${
                      r.return_type === "fresh" ? "bg-green-500/10 text-green-600" :
                      r.return_type === "replacement" ? "bg-blue-500/10 text-blue-600" :
                      "bg-red-500/10 text-red-600"
                    }`}>
                      {tr(r.return_type === "fresh" ? "freshReturn" : r.return_type === "replacement" ? "replacementReturn" : "damageReturn")}
                    </span>
                    <span className={`text-[10px] px-2 py-0.5 rounded-full ${
                      r.status === "completed" ? "bg-green-500/10 text-green-600" : "bg-yellow-500/10 text-yellow-600"
                    }`}>{r.status}</span>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    {tr("quantity")}: {r.quantity} | {r.invoice_id && `INV: ${r.invoice_id}`}
                  </p>
                  {r.refund_amount > 0 && (
                    <p className="text-xs font-semibold text-foreground">
                      <Banknote className="inline h-3 w-3 mr-1" />
                      {tr("refundAmount")}: ৳{r.refund_amount}
                    </p>
                  )}
                  <p className="text-[10px] text-muted-foreground">
                    {new Date(r.created_at).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-US")}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </PageLayout>
  );
}
