import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery, useMutation } 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 { toast } from "sonner";
import { useState } from "react";
import { Plus, Trash2, ArrowRightLeft } from "lucide-react";

export const Route = createFileRoute("/_authenticated/transfers/create")({
  component: CreateTransferPage,
});

type TransferItem = {
  product_id: string;
  product_name: string;
  quantity: string;
  unit: string;
  available: number;
};

function CreateTransferPage() {
  const { tr } = useLanguage();
  const { user } = useAuth();
  const navigate = useNavigate();
  const [fromGodown, setFromGodown] = useState("");
  const [toGodown, setToGodown] = useState("");
  const [note, setNote] = useState("");
  const [items, setItems] = useState<TransferItem[]>([]);

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

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

  // Get available stock for from_godown
  const { data: godownStocks = [] } = useQuery({
    queryKey: ["godown-stocks-from", fromGodown],
    enabled: !!fromGodown,
    queryFn: async () => {
      const { data, error } = await supabase.from("godown_stocks").select("product_id, quantity").eq("godown_id", fromGodown);
      if (error) throw error;
      return data;
    },
  });

  const stockMap: Record<string, number> = {};
  godownStocks.forEach((s: any) => { stockMap[s.product_id] = Number(s.quantity); });

  const addItem = () => {
    setItems([...items, { product_id: "", product_name: "", quantity: "", unit: "pcs", available: 0 }]);
  };

  const updateItem = (idx: number, field: string, value: string) => {
    const updated = [...items];
    if (field === "product_id") {
      const prod = products.find((p: any) => p.id === value);
      updated[idx] = { ...updated[idx], product_id: value, product_name: prod?.name || "", unit: prod?.unit || "pcs", available: stockMap[value] || 0 };
    } else {
      (updated[idx] as any)[field] = value;
    }
    setItems(updated);
  };

  const removeItem = (idx: number) => setItems(items.filter((_, i) => i !== idx));

  const mutation = useMutation({
    mutationFn: async () => {
      if (!fromGodown || !toGodown) throw new Error(tr("selectGodown"));
      if (fromGodown === toGodown) throw new Error(tr("sameGodownError"));
      if (items.length === 0) throw new Error(tr("addAtLeastOneItem"));

      // Validate quantities
      for (const item of items) {
        if (!item.product_id) throw new Error(tr("selectProduct"));
        const qty = Number(item.quantity);
        if (qty <= 0) throw new Error(tr("invalidQuantity"));
        if (qty > item.available) throw new Error(`${item.product_name}: ${tr("insufficientStock")}`);
      }

      // Create transfer (pending status - needs approval)
      const { data: transfer, error: tErr } = await supabase.from("transfers").insert({
        from_godown_id: fromGodown,
        to_godown_id: toGodown,
        note,
        total_items: items.length,
        created_by: user?.id,
        status: "pending",
      }).select("id").single();
      if (tErr) throw tErr;

      // Insert items
      const transferItems = items.map((item) => ({
        transfer_id: transfer.id,
        product_id: item.product_id,
        quantity: Number(item.quantity),
        unit: item.unit,
      }));
      const { error: iErr } = await supabase.from("transfer_items").insert(transferItems);
      if (iErr) throw iErr;
    },
    onSuccess: () => {
      toast.success(tr("transferCreated"));
      navigate({ to: "/transfers" });
    },
    onError: (e: any) => toast.error(e.message),
  });

  return (
    <PageLayout title={tr("createTransfer")} subtitle={tr("createTransferSubtitle")}>
      <div className="max-w-4xl space-y-6">
        {/* Godown Selection */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <Label>{tr("fromGodown")} *</Label>
            <Select value={fromGodown} onValueChange={(v) => { setFromGodown(v); setItems([]); }}>
              <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={toGodown} onValueChange={setToGodown}>
              <SelectTrigger><SelectValue placeholder={tr("selectGodown")} /></SelectTrigger>
              <SelectContent>{godowns.filter((g: any) => g.id !== fromGodown).map((g: any) => <SelectItem key={g.id} value={g.id}>{g.name}</SelectItem>)}</SelectContent>
            </Select>
          </div>
        </div>

        {/* Product Items */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <Label className="text-base font-semibold">{tr("transferItems")}</Label>
            <Button variant="outline" size="sm" onClick={addItem} disabled={!fromGodown}>
              <Plus className="mr-1 h-4 w-4" />{tr("addItem")}
            </Button>
          </div>

          {items.length > 0 && (
            <div className="rounded-lg border bg-card">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[40%]">{tr("productName")}</TableHead>
                    <TableHead>{tr("availableStock")}</TableHead>
                    <TableHead>{tr("quantity")}</TableHead>
                    <TableHead>{tr("unit")}</TableHead>
                    <TableHead></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {items.map((item, idx) => (
                    <TableRow key={idx}>
                      <TableCell>
                        <Select value={item.product_id} onValueChange={(v) => updateItem(idx, "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>
                      </TableCell>
                      <TableCell className="text-muted-foreground">{item.available}</TableCell>
                      <TableCell>
                        <Input type="number" min="1" max={item.available} value={item.quantity} onChange={(e) => updateItem(idx, "quantity", e.target.value)} className="w-24" />
                      </TableCell>
                      <TableCell className="text-muted-foreground">{item.unit}</TableCell>
                      <TableCell>
                        <Button variant="ghost" size="icon" onClick={() => removeItem(idx)}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}

          {items.length === 0 && fromGodown && (
            <p className="text-sm text-muted-foreground py-4 text-center border rounded-lg">{tr("addItemsToTransfer")}</p>
          )}
        </div>

        {/* Note */}
        <div>
          <Label>{tr("note")}</Label>
          <Textarea value={note} onChange={(e) => setNote(e.target.value)} />
        </div>

        <Button onClick={() => mutation.mutate()} disabled={mutation.isPending || items.length === 0} className="w-full md:w-auto">
          <ArrowRightLeft className="mr-2 h-4 w-4" />
          {mutation.isPending ? tr("saving") : tr("createTransfer")}
        </Button>
      </div>
    </PageLayout>
  );
}
