import { createFileRoute, useNavigate } 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 { useState, useEffect } from "react";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";

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

function EditSupplierPage() {
  const { supplierId } = Route.useParams();
  const { tr } = useLanguage();
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const [form, setForm] = useState({
    name: "",
    mobile: "",
    email: "",
    address: "",
    company_name: "",
    opening_balance: 0,
    status: "active",
  });

  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;
    },
  });

  useEffect(() => {
    if (supplier) {
      setForm({
        name: supplier.name || "",
        mobile: supplier.mobile || "",
        email: supplier.email || "",
        address: supplier.address || "",
        company_name: supplier.company_name || "",
        opening_balance: Number(supplier.opening_balance) || 0,
        status: supplier.status || "active",
      });
    }
  }, [supplier]);

  const set = (key: string, value: any) => setForm((p) => ({ ...p, [key]: value }));

  const updateMutation = useMutation({
    mutationFn: async () => {
      if (!form.name.trim()) throw new Error("Name required");
      if (!form.mobile.trim()) throw new Error("Mobile required");

      // Recalculate due if opening balance changed
      const balanceDiff = form.opening_balance - Number(supplier.opening_balance);
      const newDue = Math.max(0, Number(supplier.current_due) + balanceDiff);

      const { error } = await supabase.from("suppliers").update({
        name: form.name.trim(),
        mobile: form.mobile.trim(),
        email: form.email.trim(),
        address: form.address.trim(),
        company_name: form.company_name.trim(),
        opening_balance: form.opening_balance,
        current_due: newDue,
        status: form.status,
      }).eq("id", supplierId);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success(tr("supplierUpdated"));
      queryClient.invalidateQueries({ queryKey: ["suppliers"] });
      queryClient.invalidateQueries({ queryKey: ["supplier", supplierId] });
      navigate({ to: "/suppliers/$supplierId", params: { supplierId } });
    },
    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>
    );
  }

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("editSupplier")}</h1>
      </div>

      <div className="max-w-2xl rounded-xl border border-border bg-card p-6 space-y-4">
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("supplierName")} *</label>
            <input className={inputCls} value={form.name} onChange={(e) => set("name", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("mobile")} *</label>
            <input className={inputCls} value={form.mobile} onChange={(e) => set("mobile", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("email")}</label>
            <input className={inputCls} value={form.email} onChange={(e) => set("email", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("companyName")}</label>
            <input className={inputCls} value={form.company_name} onChange={(e) => set("company_name", e.target.value)} />
          </div>
          <div className="sm:col-span-2">
            <label className="text-xs font-medium text-muted-foreground">{tr("address")}</label>
            <input className={inputCls} value={form.address} onChange={(e) => set("address", e.target.value)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("openingBalance")}</label>
            <input type="number" className={inputCls} value={form.opening_balance} onChange={(e) => set("opening_balance", Number(e.target.value) || 0)} />
          </div>
          <div>
            <label className="text-xs font-medium text-muted-foreground">{tr("status")}</label>
            <select className={inputCls} value={form.status} onChange={(e) => set("status", e.target.value)}>
              <option value="active">{tr("active")}</option>
              <option value="inactive">{tr("inactive")}</option>
            </select>
          </div>
        </div>

        <button
          onClick={() => updateMutation.mutate()}
          disabled={updateMutation.isPending}
          className="mt-4 rounded-lg bg-primary px-6 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2"
        >
          {updateMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
          {tr("save")}
        </button>
      </div>
    </PageLayout>
  );
}
