import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { AlertTriangle, PackageX, RotateCcw, TrendingDown, Printer, Download, Eye } from "lucide-react";
import { exportCSV } from "@/lib/export-utils";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";

export const Route = createFileRoute("/_authenticated/damage-report")({
  head: () => ({ meta: [{ title: "Damage & Return Loss Report — Niyamah ERP" }] }),
  component: DamageReportPage,
});

function DamageReportPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const today = new Date().toISOString().slice(0, 10);
  const monthAgo = new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10);
  const [from, setFrom] = useState(monthAgo);
  const [to, setTo] = useState(today);
  const [selectedDamage, setSelectedDamage] = useState<any | null>(null);
  const [selectedReturn, setSelectedReturn] = useState<any | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["damage-report", from, to],
    queryFn: async () => {
      const [damageRes, returnsRes, productsRes] = await Promise.all([
        supabase
          .from("damage_stock")
          .select("*, products(name, name_bn, sku, purchase_price)")
          .gte("created_at", from)
          .lte("created_at", to + "T23:59:59"),
        supabase
          .from("sales_returns")
          .select("*, products(name, name_bn, sku, purchase_price), customers(name)")
          .gte("created_at", from)
          .lte("created_at", to + "T23:59:59"),
        supabase.from("products").select("id, name, name_bn, sku, purchase_price"),
      ]);
      return {
        damages: (damageRes.data as any[]) || [],
        returns: (returnsRes.data as any[]) || [],
        products: (productsRes.data as any[]) || [],
      };
    },
  });

  const summary = useMemo(() => {
    const damages = data?.damages || [];
    const returns = data?.returns || [];
    const damageQty = damages.reduce((s, d) => s + Number(d.quantity || 0), 0);
    const damageValue = damages.reduce(
      (s, d) => s + Number(d.quantity || 0) * Number(d.products?.purchase_price || 0),
      0
    );
    const returnQty = returns.reduce((s, r) => s + Number(r.quantity || 0), 0);
    const returnLoss = returns.reduce((s, r) => s + Number(r.refund_amount || 0), 0);
    const damageReturnQty = damages
      .filter((d) => d.source === "return")
      .reduce((s, d) => s + Number(d.quantity || 0), 0);
    return {
      damageQty,
      damageValue,
      returnQty,
      returnLoss,
      damageReturnQty,
      totalLoss: damageValue + returnLoss,
      damageCount: damages.length,
      returnCount: returns.length,
    };
  }, [data]);

  const bySource = useMemo(() => {
    const map: Record<string, { qty: number; value: number; count: number }> = {};
    (data?.damages || []).forEach((d) => {
      const k = d.source || "other";
      if (!map[k]) map[k] = { qty: 0, value: 0, count: 0 };
      map[k].qty += Number(d.quantity || 0);
      map[k].value += Number(d.quantity || 0) * Number(d.products?.purchase_price || 0);
      map[k].count += 1;
    });
    return map;
  }, [data]);

  const handleExport = () => {
    const rows = [
      ...(data?.damages || []).map((d) => ({
        Type: "Damage",
        Date: new Date(d.created_at).toLocaleDateString(),
        Product: d.products?.name || "",
        SKU: d.products?.sku || "",
        Source: d.source,
        Quantity: d.quantity,
        UnitCost: d.products?.purchase_price || 0,
        Loss: Number(d.quantity) * Number(d.products?.purchase_price || 0),
        Note: d.note || "",
      })),
      ...(data?.returns || []).map((r) => ({
        Type: "Return",
        Date: new Date(r.created_at).toLocaleDateString(),
        Product: r.products?.name || "",
        SKU: r.products?.sku || "",
        Source: r.return_type,
        Quantity: r.quantity,
        UnitCost: r.products?.purchase_price || 0,
        Loss: r.refund_amount,
        Note: r.reason || "",
      })),
    ];
    exportCSV(`damage-return-report-${from}-${to}`, rows);
  };

  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-end justify-between gap-3 print:hidden">
        <div>
          <h1 className="text-xl font-bold flex items-center gap-2">
            <AlertTriangle className="h-5 w-5 text-orange-500" />
            {isBn ? "ক্ষতি ও রিটার্ন রিপোর্ট" : "Damage & Return Loss Report"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {isBn ? "ড্যামেজ স্টক, ক্ষতির মূল্য ও রিটার্ন ট্র্যাকিং" : "Damage stock, loss value & return tracking"}
          </p>
        </div>
        <div className="flex flex-wrap items-end gap-2">
          <div>
            <label className="block text-xs text-muted-foreground">{isBn ? "শুরু" : "From"}</label>
            <input type="date" value={from} onChange={(e) => setFrom(e.target.value)}
              className="rounded-lg border border-border bg-background px-3 py-2 text-sm" />
          </div>
          <div>
            <label className="block text-xs text-muted-foreground">{isBn ? "শেষ" : "To"}</label>
            <input type="date" value={to} onChange={(e) => setTo(e.target.value)}
              className="rounded-lg border border-border bg-background px-3 py-2 text-sm" />
          </div>
          <button onClick={handleExport}
            className="flex items-center gap-1 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted">
            <Download className="h-4 w-4" />CSV
          </button>
          <button onClick={() => window.print()}
            className="flex items-center gap-1 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted">
            <Printer className="h-4 w-4" />{isBn ? "প্রিন্ট" : "Print"}
          </button>
        </div>
      </div>

      {isLoading ? (
        <div className="p-8 text-center text-muted-foreground">Loading...</div>
      ) : (
        <>
          {/* Summary KPI cards */}
          <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
            <KpiCard icon={PackageX} color="text-orange-600" bg="bg-orange-100 dark:bg-orange-900/20"
              label={isBn ? "ড্যামেজ স্টক ভ্যালু" : "Damage Stock Value"}
              value={`৳${summary.damageValue.toLocaleString()}`}
              sub={`${summary.damageQty} ${isBn ? "একক" : "units"}`} />
            <KpiCard icon={RotateCcw} color="text-rose-600" bg="bg-rose-100 dark:bg-rose-900/20"
              label={isBn ? "রিটার্ন লস" : "Return Loss"}
              value={`৳${summary.returnLoss.toLocaleString()}`}
              sub={`${summary.returnCount} ${isBn ? "রিটার্ন" : "returns"}`} />
            <KpiCard icon={AlertTriangle} color="text-amber-600" bg="bg-amber-100 dark:bg-amber-900/20"
              label={isBn ? "ড্যামেজ আইটেম" : "Damaged Items"}
              value={`${summary.damageCount}`}
              sub={`${summary.damageReturnQty} ${isBn ? "রিটার্ন থেকে" : "from returns"}`} />
            <KpiCard icon={TrendingDown} color="text-red-600" bg="bg-red-100 dark:bg-red-900/20"
              label={isBn ? "মোট ক্ষতি" : "Total Loss"}
              value={`৳${summary.totalLoss.toLocaleString()}`}
              sub={isBn ? "ড্যামেজ + রিটার্ন" : "Damage + Return"} />
          </div>

          {/* Source breakdown */}
          <div className="mb-6 rounded-xl border border-border bg-card p-5">
            <h3 className="mb-4 text-sm font-bold flex items-center gap-2">
              <PackageX className="h-4 w-4 text-orange-500" />
              {isBn ? "উৎস অনুযায়ী ক্ষতি বিভাজন" : "Loss Breakdown by Source"}
            </h3>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
              {Object.entries(bySource).map(([src, v]) => (
                <div key={src} className="rounded-lg border border-border p-3">
                  <div className="text-xs uppercase text-muted-foreground">{src}</div>
                  <div className="mt-1 text-lg font-bold text-foreground">৳{v.value.toLocaleString()}</div>
                  <div className="text-xs text-muted-foreground">{v.qty} {isBn ? "একক" : "units"} · {v.count} {isBn ? "রেকর্ড" : "records"}</div>
                </div>
              ))}
              {Object.keys(bySource).length === 0 && (
                <div className="text-sm text-muted-foreground col-span-3 text-center py-4">
                  {isBn ? "কোনো তথ্য নেই" : "No data"}
                </div>
              )}
            </div>
          </div>

          {/* Damage Stock Table */}
          <div className="mb-6 rounded-xl border border-border bg-card p-5">
            <h3 className="mb-4 text-sm font-bold flex items-center gap-2">
              <PackageX className="h-4 w-4 text-orange-500" />
              {isBn ? "ড্যামেজ স্টক বিস্তারিত" : "Damage Stock Details"}
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs uppercase text-muted-foreground">
                    <th className="py-2">{isBn ? "তারিখ" : "Date"}</th>
                    <th className="py-2">{isBn ? "পণ্য" : "Product"}</th>
                    <th className="py-2">{isBn ? "উৎস" : "Source"}</th>
                    <th className="py-2 text-right">{isBn ? "পরিমাণ" : "Qty"}</th>
                    <th className="py-2 text-right">{isBn ? "ইউনিট মূল্য" : "Unit Cost"}</th>
                    <th className="py-2 text-right">{isBn ? "ক্ষতি" : "Loss"}</th>
                    <th className="py-2 text-right">{isBn ? "অ্যাকশন" : "Action"}</th>
                  </tr>
                </thead>
                <tbody>
                  {(data?.damages || []).map((d) => {
                    const loss = Number(d.quantity) * Number(d.products?.purchase_price || 0);
                    return (
                      <tr key={d.id} className="border-b border-border/30 hover:bg-muted/40 cursor-pointer" onClick={() => setSelectedDamage(d)}>
                        <td className="py-2">{new Date(d.created_at).toLocaleDateString()}</td>
                        <td className="py-2">
                          <div className="font-medium">{d.products?.name}</div>
                          <div className="text-xs text-muted-foreground">{d.products?.sku}</div>
                        </td>
                        <td className="py-2"><span className="rounded-full bg-secondary px-2 py-0.5 text-xs">{d.source}</span></td>
                        <td className="py-2 text-right">{d.quantity}</td>
                        <td className="py-2 text-right">৳{Number(d.products?.purchase_price || 0).toLocaleString()}</td>
                        <td className="py-2 text-right font-semibold text-orange-600">৳{loss.toLocaleString()}</td>
                        <td className="py-2 text-right" onClick={(e) => e.stopPropagation()}>
                          <button onClick={() => setSelectedDamage(d)} className="inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs hover:bg-muted">
                            <Eye className="h-3 w-3" />{isBn ? "দেখুন" : "View"}
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                  {(data?.damages.length || 0) === 0 && (
                    <tr><td colSpan={7} className="py-6 text-center text-muted-foreground">{isBn ? "কোনো ড্যামেজ রেকর্ড নেই" : "No damage records"}</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          {/* Sales Return Table */}
          <div className="rounded-xl border border-border bg-card p-5">
            <h3 className="mb-4 text-sm font-bold flex items-center gap-2">
              <RotateCcw className="h-4 w-4 text-rose-500" />
              {isBn ? "সেলস রিটার্ন বিস্তারিত" : "Sales Return Details"}
            </h3>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-border text-left text-xs uppercase text-muted-foreground">
                    <th className="py-2">{isBn ? "তারিখ" : "Date"}</th>
                    <th className="py-2">{isBn ? "ইনভয়েস" : "Invoice"}</th>
                    <th className="py-2">{isBn ? "গ্রাহক" : "Customer"}</th>
                    <th className="py-2">{isBn ? "পণ্য" : "Product"}</th>
                    <th className="py-2">{isBn ? "ধরন" : "Type"}</th>
                    <th className="py-2 text-right">{isBn ? "পরিমাণ" : "Qty"}</th>
                    <th className="py-2 text-right">{isBn ? "রিফান্ড" : "Refund"}</th>
                    <th className="py-2 text-right">{isBn ? "অ্যাকশন" : "Action"}</th>
                  </tr>
                </thead>
                <tbody>
                  {(data?.returns || []).map((r) => (
                    <tr key={r.id} className="border-b border-border/30 hover:bg-muted/40 cursor-pointer" onClick={() => setSelectedReturn(r)}>
                      <td className="py-2">{new Date(r.created_at).toLocaleDateString()}</td>
                      <td className="py-2 font-mono text-xs">{r.invoice_id}</td>
                      <td className="py-2">{r.customers?.name || "-"}</td>
                      <td className="py-2">
                        <div className="font-medium">{r.products?.name}</div>
                        <div className="text-xs text-muted-foreground">{r.products?.sku}</div>
                      </td>
                      <td className="py-2"><span className="rounded-full bg-secondary px-2 py-0.5 text-xs">{r.return_type}</span></td>
                      <td className="py-2 text-right">{r.quantity}</td>
                      <td className="py-2 text-right font-semibold text-rose-600">৳{Number(r.refund_amount).toLocaleString()}</td>
                      <td className="py-2 text-right" onClick={(e) => e.stopPropagation()}>
                        <button onClick={() => setSelectedReturn(r)} className="inline-flex items-center gap-1 rounded-md border border-border px-2 py-1 text-xs hover:bg-muted">
                          <Eye className="h-3 w-3" />{isBn ? "দেখুন" : "View"}
                        </button>
                      </td>
                    </tr>
                  ))}
                  {(data?.returns.length || 0) === 0 && (
                    <tr><td colSpan={8} className="py-6 text-center text-muted-foreground">{isBn ? "কোনো রিটার্ন নেই" : "No returns"}</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

          <DamageDetailDialog record={selectedDamage} onClose={() => setSelectedDamage(null)} isBn={isBn} />
          <ReturnDetailDialog record={selectedReturn} onClose={() => setSelectedReturn(null)} isBn={isBn} />
        </>
      )}
    </PageLayout>
  );
}

function KpiCard({ icon: Icon, color, bg, label, value, sub }: any) {
  return (
    <div className="rounded-xl border border-border bg-card p-5">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-xs text-muted-foreground">{label}</p>
          <p className="mt-1 text-xl font-bold text-foreground">{value}</p>
          <p className="mt-1 text-xs text-muted-foreground">{sub}</p>
        </div>
        <div className={`rounded-lg p-2 ${bg}`}>
          <Icon className={`h-5 w-5 ${color}`} />
        </div>
      </div>
    </div>
  );
}

function Field({ label, value, mono = false }: { label: string; value: any; mono?: boolean }) {
  return (
    <div>
      <div className="text-xs uppercase text-muted-foreground">{label}</div>
      <div className={`mt-0.5 text-sm font-medium ${mono ? "font-mono" : ""}`}>{value ?? "-"}</div>
    </div>
  );
}

function DamageDetailDialog({ record, onClose, isBn }: { record: any; onClose: () => void; isBn: boolean }) {
  if (!record) return null;
  const unit = Number(record.products?.purchase_price || 0);
  const qty = Number(record.quantity || 0);
  const loss = unit * qty;
  return (
    <Dialog open={!!record} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <PackageX className="h-5 w-5 text-orange-500" />
            {isBn ? "ড্যামেজ বিস্তারিত" : "Damage Details"}
          </DialogTitle>
          <DialogDescription className="font-mono text-xs">{record.id}</DialogDescription>
        </DialogHeader>
        <div className="grid grid-cols-2 gap-4">
          <Field label={isBn ? "তারিখ" : "Date"} value={new Date(record.created_at).toLocaleString()} />
          <Field label={isBn ? "উৎস" : "Source"} value={record.source} />
          <Field label={isBn ? "পণ্য" : "Product"} value={record.products?.name} />
          <Field label="SKU" value={record.products?.sku} mono />
          <Field label={isBn ? "পরিমাণ" : "Quantity"} value={qty} />
          <Field label={isBn ? "ইউনিট মূল্য" : "Unit Cost"} value={`৳${unit.toLocaleString()}`} />
          <Field label={isBn ? "মোট ক্ষতি" : "Total Loss"} value={<span className="text-orange-600 font-bold">৳{loss.toLocaleString()}</span>} />
          {record.reference_id && (
            <Field label={isBn ? "রেফারেন্স" : "Reference"} value={record.reference_id} mono />
          )}
        </div>
        <div className="rounded-lg border border-border bg-muted/30 p-3">
          <div className="text-xs uppercase text-muted-foreground mb-1">{isBn ? "নোট" : "Note"}</div>
          <div className="text-sm whitespace-pre-wrap">{record.note || (isBn ? "কোনো নোট নেই" : "No note")}</div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

function ReturnDetailDialog({ record, onClose, isBn }: { record: any; onClose: () => void; isBn: boolean }) {
  if (!record) return null;
  return (
    <Dialog open={!!record} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <RotateCcw className="h-5 w-5 text-rose-500" />
            {isBn ? "রিটার্ন বিস্তারিত" : "Return Details"}
          </DialogTitle>
          <DialogDescription className="font-mono text-xs">{record.id}</DialogDescription>
        </DialogHeader>
        <div className="grid grid-cols-2 gap-4">
          <Field label={isBn ? "তারিখ" : "Date"} value={new Date(record.created_at).toLocaleString()} />
          <Field label={isBn ? "ইনভয়েস" : "Invoice"} value={record.invoice_id} mono />
          <Field label={isBn ? "গ্রাহক" : "Customer"} value={record.customers?.name} />
          <Field label={isBn ? "ধরন" : "Type"} value={record.return_type} />
          <Field label={isBn ? "স্ট্যাটাস" : "Status"} value={record.status} />
          <Field label={isBn ? "পণ্য" : "Product"} value={record.products?.name} />
          <Field label="SKU" value={record.products?.sku} mono />
          <Field label={isBn ? "পরিমাণ" : "Quantity"} value={Number(record.quantity || 0)} />
          <Field label={isBn ? "রিফান্ড" : "Refund"} value={<span className="text-rose-600 font-bold">৳{Number(record.refund_amount || 0).toLocaleString()}</span>} />
          {record.replacement_product_id && (
            <Field label={isBn ? "রিপ্লেসমেন্ট পণ্য" : "Replacement Product"} value={record.replacement_product_id} mono />
          )}
        </div>
        <div className="rounded-lg border border-border bg-muted/30 p-3">
          <div className="text-xs uppercase text-muted-foreground mb-1">{isBn ? "কারণ" : "Reason"}</div>
          <div className="text-sm whitespace-pre-wrap">{record.reason || (isBn ? "কোনো কারণ লেখা নেই" : "No reason provided")}</div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
