import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { useState } from "react";
import { ArrowRightLeft } from "lucide-react";

export const Route = createFileRoute("/_authenticated/godowns/transfer")({
  component: StockTransferPage,
});

function StockTransferPage() {
  const { tr } = useLanguage();
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [form, setForm] = useState({ from_godown_id: "", to_godown_id: "", product_id: "", quantity: "", note: "" });

  const { data: godowns = [] } = useQuery({
    queryKey: ["godowns"],
    queryFn: async () => {
      const { data, error } = await supabase.from("godowns").select("*").eq("status", "active").order("name");
      if (error) throw error;
      return data;
    },
  });

  const { data: products = [] } = useQuery({
    queryKey: ["products-active"],
    queryFn: async () => {
      const { data, error } = await supabase.from("products").select("id, name, sku").eq("is_deleted", false).order("name");
      if (error) throw error;
      return data;
    },
  });

  const { data: availableQty } = useQuery({
    queryKey: ["godown-stock-qty", form.from_godown_id, form.product_id],
    enabled: !!form.from_godown_id && !!form.product_id,
    queryFn: async () => {
      const { data } = await supabase.from("godown_stocks").select("quantity").eq("godown_id", form.from_godown_id).eq("product_id", form.product_id).maybeSingle();
      return data?.quantity ?? 0;
    },
  });

  const { data: transfers = [] } = useQuery({
    queryKey: ["stock-transfers-recent"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("stock_transfers")
        .select("*, from_godown:from_godown_id(name), to_godown:to_godown_id(name), products:product_id(name)")
        .order("created_at", { ascending: false })
        .limit(50);
      if (error) throw error;
      return data;
    },
  });

  const transferMutation = useMutation({
    mutationFn: async () => {
      const qty = Number(form.quantity);
      if (qty <= 0) throw new Error("Quantity must be > 0");
      if (qty > Number(availableQty)) throw new Error(tr("insufficientStock"));
      if (form.from_godown_id === form.to_godown_id) throw new Error("Same godown");

      // Insert transfer record
      const { error: tErr } = await supabase.from("stock_transfers").insert({
        from_godown_id: form.from_godown_id,
        to_godown_id: form.to_godown_id,
        product_id: form.product_id,
        quantity: qty,
        note: form.note,
        transferred_by: user?.id,
      });
      if (tErr) throw tErr;

      // Decrease from godown
      const { data: fromStock } = await supabase.from("godown_stocks").select("id, quantity").eq("godown_id", form.from_godown_id).eq("product_id", form.product_id).single();
      if (fromStock) {
        await supabase.from("godown_stocks").update({ quantity: Number(fromStock.quantity) - qty }).eq("id", fromStock.id);
      }

      // Increase to godown (upsert)
      const { data: toStock } = await supabase.from("godown_stocks").select("id, quantity").eq("godown_id", form.to_godown_id).eq("product_id", form.product_id).maybeSingle();
      if (toStock) {
        await supabase.from("godown_stocks").update({ quantity: Number(toStock.quantity) + qty }).eq("id", toStock.id);
      } else {
        await supabase.from("godown_stocks").insert({ godown_id: form.to_godown_id, product_id: form.product_id, quantity: qty });
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["godown-stocks"] });
      queryClient.invalidateQueries({ queryKey: ["godown-stock-summary"] });
      queryClient.invalidateQueries({ queryKey: ["stock-transfers-recent"] });
      toast.success(tr("transferSuccess"));
      setForm({ from_godown_id: "", to_godown_id: "", product_id: "", quantity: "", note: "" });
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <PageLayout title={tr("stockTransfer")} subtitle={tr("stockTransferSubtitle")}>
      <Tabs defaultValue="new">
        <TabsList>
          <TabsTrigger value="new">{tr("newTransfer")}</TabsTrigger>
          <TabsTrigger value="history">{tr("transferHistory")}</TabsTrigger>
        </TabsList>

        <TabsContent value="new">
          <div className="max-w-xl space-y-4 mt-4">
            <div>
              <Label>{tr("fromGodown")} *</Label>
              <Select value={form.from_godown_id} onValueChange={(v) => setForm({ ...form, from_godown_id: v })}>
                <SelectTrigger><SelectValue placeholder={tr("selectGodown")} /></SelectTrigger>
                <SelectContent>{godowns.map((g: any) => <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div>
              <Label>{tr("toGodown")} *</Label>
              <Select value={form.to_godown_id} onValueChange={(v) => setForm({ ...form, to_godown_id: v })}>
                <SelectTrigger><SelectValue placeholder={tr("selectGodown")} /></SelectTrigger>
                <SelectContent>{godowns.filter((g: any) => g.id !== form.from_godown_id).map((g: any) => <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div>
              <Label>{tr("productName")} *</Label>
              <Select value={form.product_id} onValueChange={(v) => setForm({ ...form, product_id: v })}>
                <SelectTrigger><SelectValue placeholder={tr("selectProduct")} /></SelectTrigger>
                <SelectContent>{products.map((p: any) => <SelectItem key={p.id} value={p.id}>{p.name} ({p.sku})</SelectItem>)}</SelectContent>
              </Select>
              {form.from_godown_id && form.product_id && (
                <p className="text-xs text-muted-foreground mt-1">{tr("availableStock")}: {availableQty ?? 0}</p>
              )}
            </div>
            <div>
              <Label>{tr("quantity")} *</Label>
              <Input type="number" min="1" max={Number(availableQty) || undefined} value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} />
            </div>
            <div>
              <Label>{tr("note")}</Label>
              <Textarea value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} />
            </div>
            <Button onClick={() => transferMutation.mutate()} disabled={!form.from_godown_id || !form.to_godown_id || !form.product_id || !form.quantity || transferMutation.isPending}>
              <ArrowRightLeft className="mr-2 h-4 w-4" />
              {transferMutation.isPending ? tr("saving") : tr("transferStock")}
            </Button>
          </div>
        </TabsContent>

        <TabsContent value="history">
          <div className="mt-4 rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{tr("date")}</TableHead>
                  <TableHead>{tr("productName")}</TableHead>
                  <TableHead>{tr("fromGodown")}</TableHead>
                  <TableHead>{tr("toGodown")}</TableHead>
                  <TableHead>{tr("quantity")}</TableHead>
                  <TableHead>{tr("note")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {transfers.length === 0 ? (
                  <TableRow><TableCell colSpan={6} className="text-center py-6 text-muted-foreground">{tr("noData")}</TableCell></TableRow>
                ) : transfers.map((t: any) => (
                  <TableRow key={t.id}>
                    <TableCell>{new Date(t.transfer_date).toLocaleDateString()}</TableCell>
                    <TableCell>{(t.products as any)?.name || "—"}</TableCell>
                    <TableCell>{(t.from_godown as any)?.name || "—"}</TableCell>
                    <TableCell>{(t.to_godown as any)?.name || "—"}</TableCell>
                    <TableCell>{t.quantity}</TableCell>
                    <TableCell>{t.note || "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </TabsContent>
      </Tabs>
    </PageLayout>
  );
}
