import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
import { toast } from "sonner";
import { Loader2, Edit2, CreditCard, ArrowLeft } from "lucide-react";

export const Route = createFileRoute("/_authenticated/suppliers/$supplierId")({
  head: () => ({
    meta: [{ title: "Supplier Profile — Niyamah ERP" }],
  }),
  component: SupplierProfilePage,
});

function SupplierProfilePage() {
  const { supplierId } = Route.useParams();
  const { tr } = useLanguage();
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [showPayment, setShowPayment] = useState(false);
  const [payAmount, setPayAmount] = useState(0);
  const [payMethod, setPayMethod] = useState("cash");
  const [payNote, setPayNote] = useState("");
  const [activeTab, setActiveTab] = useState<"purchases" | "payments" | "ledger">("purchases");

  const { data: supplier, isLoading } = useQuery({
    queryKey: ["supplier", supplierId],
    queryFn: async () => {
      const { data, error } = await supabase.from("suppliers").select("*").eq("id", supplierId).single();
      if (error) throw error;
      return data as any;
    },
  });

  const { data: purchases = [] } = useQuery({
    queryKey: ["supplier-purchases", supplierId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("purchases")
        .select("*")
        .eq("supplier_id", supplierId)
        .order("created_at", { ascending: false })
        .limit(50);
      if (error) throw error;
      return data as any[];
    },
  });

  const { data: transactions = [] } = useQuery({
    queryKey: ["supplier-transactions", supplierId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("supplier_transactions")
        .select("*")
        .eq("supplier_id", supplierId)
        .order("created_at", { ascending: false })
        .limit(100);
      if (error) throw error;
      return data as any[];
    },
  });

  const paymentMutation = useMutation({
    mutationFn: async () => {
      if (payAmount <= 0) throw new Error("Amount must be > 0");

      // Insert transaction
      const { error: txErr } = await supabase.from("supplier_transactions").insert({
        supplier_id: supplierId,
        type: "payment",
        amount: payAmount,
        method: payMethod,
        note: payNote,
      });
      if (txErr) throw txErr;

      // Update supplier totals
      const newPaid = Number(supplier.total_paid) + payAmount;
      const newDue = Number(supplier.opening_balance) + Number(supplier.total_purchase) - newPaid;
      const { error: upErr } = await supabase
        .from("suppliers")
        .update({ total_paid: newPaid, current_due: Math.max(0, newDue) })
        .eq("id", supplierId);
      if (upErr) throw upErr;
    },
    onSuccess: () => {
      toast.success(tr("paymentSuccess"));
      setShowPayment(false);
      setPayAmount(0);
      setPayNote("");
      queryClient.invalidateQueries({ queryKey: ["supplier", supplierId] });
      queryClient.invalidateQueries({ queryKey: ["supplier-transactions", supplierId] });
      queryClient.invalidateQueries({ queryKey: ["suppliers"] });
    },
    onError: (err: any) => toast.error(err.message),
  });

  const inputCls = "w-full rounded-lg border border-border bg-card px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/40";

  if (isLoading) {
    return (
      <PageLayout>
        <div className="flex h-60 items-center justify-center"><Loader2 className="h-6 w-6 animate-spin text-primary" /></div>
      </PageLayout>
    );
  }

  if (!supplier) {
    return (
      <PageLayout>
        <p className="text-muted-foreground">{tr("noData")}</p>
      </PageLayout>
    );
  }

  const payments = transactions.filter((t: any) => t.type === "payment");

  return (
    <PageLayout>
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <Link to="/suppliers" className="text-muted-foreground hover:text-foreground">
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <h1 className="text-xl font-bold text-foreground">{supplier.name}</h1>
            <p className="text-sm text-muted-foreground">📞 {supplier.mobile} {supplier.company_name ? `| 🏢 ${supplier.company_name}` : ""}</p>
          </div>
        </div>
        <div className="flex gap-2">
          <Link
            to="/suppliers/$supplierId/edit"
            params={{ supplierId }}
            className="inline-flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium hover:bg-muted"
          >
            <Edit2 className="h-4 w-4" /> {tr("editSupplier")}
          </Link>
          <button
            onClick={() => setShowPayment(true)}
            className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90"
          >
            <CreditCard className="h-4 w-4" /> {tr("makePayment")}
          </button>
        </div>
      </div>

      {/* Account Summary */}
      <div className="mb-6 grid gap-4 sm:grid-cols-4">
        {[
          { label: tr("openingBalance"), value: supplier.opening_balance, color: "text-foreground" },
          { label: tr("totalPurchase"), value: supplier.total_purchase, color: "text-blue-500" },
          { label: tr("totalPaid"), value: supplier.total_paid, color: "text-green-500" },
          { label: tr("currentDue"), value: supplier.current_due, color: Number(supplier.current_due) > 0 ? "text-red-500" : "text-green-500" },
        ].map((card) => (
          <div key={card.label} className="rounded-xl border border-border bg-card p-4">
            <p className="text-xs text-muted-foreground">{card.label}</p>
            <p className={`text-lg font-bold ${card.color}`}>৳{Number(card.value).toLocaleString()}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="mb-4 flex gap-1 rounded-lg bg-muted p-1 w-fit">
        {(["purchases", "payments", "ledger"] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`rounded-md px-4 py-1.5 text-sm font-medium transition-colors ${
              activeTab === tab ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"
            }`}
          >
            {tab === "purchases" ? tr("purchaseHistory") : tab === "payments" ? tr("paymentHistory") : tr("ledger")}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="rounded-xl border border-border bg-card overflow-x-auto">
        {activeTab === "purchases" && (
          purchases.length === 0 ? (
            <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">{tr("noData")}</div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border text-left">
                  <th className="px-4 py-3 font-medium">{tr("invoiceNo")}</th>
                  <th className="px-4 py-3 font-medium">{tr("purchaseDate")}</th>
                  <th className="px-4 py-3 font-medium text-right">{tr("total")}</th>
                  <th className="px-4 py-3 font-medium text-right">{tr("paidAmount")}</th>
                  <th className="px-4 py-3 font-medium text-right">{tr("dueAmount")}</th>
                </tr>
              </thead>
              <tbody>
                {purchases.map((p: any) => (
                  <tr key={p.id} className="border-b border-border/30">
                    <td className="px-4 py-3">{p.invoice_no || "—"}</td>
                    <td className="px-4 py-3">{new Date(p.purchase_date).toLocaleDateString()}</td>
                    <td className="px-4 py-3 text-right">৳{Number(p.total_amount).toLocaleString()}</td>
                    <td className="px-4 py-3 text-right">৳{Number(p.paid_amount).toLocaleString()}</td>
                    <td className="px-4 py-3 text-right text-red-500">৳{Number(p.due_amount).toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        )}

        {activeTab === "payments" && (
          payments.length === 0 ? (
            <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">{tr("noData")}</div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border text-left">
                  <th className="px-4 py-3 font-medium">{tr("date")}</th>
                  <th className="px-4 py-3 font-medium text-right">{tr("amount")}</th>
                  <th className="px-4 py-3 font-medium">{tr("paymentMethod")}</th>
                  <th className="px-4 py-3 font-medium">{tr("note")}</th>
                </tr>
              </thead>
              <tbody>
                {payments.map((t: any) => (
                  <tr key={t.id} className="border-b border-border/30">
                    <td className="px-4 py-3">{new Date(t.created_at).toLocaleDateString()}</td>
                    <td className="px-4 py-3 text-right text-green-500 font-medium">৳{Number(t.amount).toLocaleString()}</td>
                    <td className="px-4 py-3 capitalize">{t.method}</td>
                    <td className="px-4 py-3 text-muted-foreground">{t.note || "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        )}

        {activeTab === "ledger" && (
          transactions.length === 0 ? (
            <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">{tr("noData")}</div>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border text-left">
                  <th className="px-4 py-3 font-medium">{tr("date")}</th>
                  <th className="px-4 py-3 font-medium">{tr("transactionType")}</th>
                  <th className="px-4 py-3 font-medium text-right">{tr("amount")}</th>
                  <th className="px-4 py-3 font-medium">{tr("paymentMethod")}</th>
                  <th className="px-4 py-3 font-medium">{tr("note")}</th>
                </tr>
              </thead>
              <tbody>
                {transactions.map((t: any) => (
                  <tr key={t.id} className="border-b border-border/30">
                    <td className="px-4 py-3">{new Date(t.created_at).toLocaleDateString()}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${
                        t.type === "purchase" ? "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400" : "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
                      }`}>
                        {t.type === "purchase" ? tr("purchase") : tr("payment")}
                      </span>
                    </td>
                    <td className={`px-4 py-3 text-right font-medium ${t.type === "purchase" ? "text-red-500" : "text-green-500"}`}>
                      {t.type === "purchase" ? "+" : "-"}৳{Number(t.amount).toLocaleString()}
                    </td>
                    <td className="px-4 py-3 capitalize">{t.method}</td>
                    <td className="px-4 py-3 text-muted-foreground">{t.note || "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )
        )}
      </div>

      {/* Payment Modal */}
      {showPayment && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="w-full max-w-md rounded-xl border border-border bg-card p-6 space-y-4">
            <h3 className="text-lg font-bold text-foreground">{tr("makePayment")}</h3>
            <p className="text-sm text-muted-foreground">{supplier.name} — {tr("currentDue")}: ৳{Number(supplier.current_due).toLocaleString()}</p>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("amount")}</label>
              <input type="number" className={inputCls} value={payAmount} onChange={(e) => setPayAmount(Number(e.target.value) || 0)} />
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("paymentMethod")}</label>
              <select className={inputCls} value={payMethod} onChange={(e) => setPayMethod(e.target.value)}>
                <option value="cash">{tr("cash")}</option>
                <option value="bank">{tr("bankTransfer")}</option>
                <option value="bkash">{tr("bkash")}</option>
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-muted-foreground">{tr("note")}</label>
              <input className={inputCls} value={payNote} onChange={(e) => setPayNote(e.target.value)} />
            </div>
            <div className="flex gap-3 pt-2">
              <button
                onClick={() => setShowPayment(false)}
                className="flex-1 rounded-lg border border-border px-4 py-2 text-sm font-medium hover:bg-muted"
              >
                {tr("cancel")}
              </button>
              <button
                onClick={() => paymentMutation.mutate()}
                disabled={paymentMutation.isPending}
                className="flex-1 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {paymentMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                {tr("save")}
              </button>
            </div>
          </div>
        </div>
      )}
    </PageLayout>
  );
}
