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 { usePermissions } from "@/hooks/use-permissions";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";
import { CheckCircle, XCircle, ArrowRight } from "lucide-react";

export const Route = createFileRoute("/_authenticated/transfers/$transferId")({
  component: TransferDetailPage,
});

function TransferDetailPage() {
  const { transferId } = Route.useParams();
  const { tr } = useLanguage();
  const { user } = useAuth();
  const { isAdmin } = usePermissions();
  const queryClient = useQueryClient();

  const { data: transfer } = useQuery({
    queryKey: ["transfer", transferId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("transfers")
        .select("*, from_godown:from_godown_id(name), to_godown:to_godown_id(name)")
        .eq("id", transferId)
        .single();
      if (error) throw error;
      return data;
    },
  });

  const { data: items = [] } = useQuery({
    queryKey: ["transfer-items", transferId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("transfer_items")
        .select("*, products:product_id(name, sku)")
        .eq("transfer_id", transferId);
      if (error) throw error;
      return data;
    },
  });

  const approveMutation = useMutation({
    mutationFn: async () => {
      // Execute stock movement for each item
      for (const item of items) {
        const qty = Number((item as any).quantity);
        const productId = (item as any).product_id;

        // Decrease from godown
        const { data: fromStock } = await supabase.from("godown_stocks")
          .select("id, quantity").eq("godown_id", transfer!.from_godown_id).eq("product_id", productId).single();

        if (!fromStock || Number(fromStock.quantity) < qty) {
          throw new Error(`${(item as any).products?.name}: ${tr("insufficientStock")}`);
        }
        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", transfer!.to_godown_id).eq("product_id", productId).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: transfer!.to_godown_id, product_id: productId, quantity: qty });
        }
      }

      // Mark transfer as approved
      const { error } = await supabase.from("transfers").update({
        status: "approved",
        approved_by: user?.id,
        approved_at: new Date().toISOString(),
      }).eq("id", transferId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["transfer", transferId] });
      queryClient.invalidateQueries({ queryKey: ["transfers-list"] });
      queryClient.invalidateQueries({ queryKey: ["godown-stocks"] });
      queryClient.invalidateQueries({ queryKey: ["godown-stock-summary"] });
      toast.success(tr("transferApproved"));
    },
    onError: (e: any) => toast.error(e.message),
  });

  const cancelMutation = useMutation({
    mutationFn: async () => {
      const { error } = await supabase.from("transfers").update({ status: "cancelled" }).eq("id", transferId);
      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["transfer", transferId] });
      queryClient.invalidateQueries({ queryKey: ["transfers-list"] });
      toast.success(tr("transferCancelled"));
    },
  });

  if (!transfer) return null;

  const statusColor = (s: string) => {
    if (s === "approved") return "default";
    if (s === "pending") return "outline";
    return "destructive";
  };

  return (
    <PageLayout title={`${tr("transferDetails")} — ${transfer.transfer_no}`}>
      {/* Summary */}
      <div className="grid gap-4 md:grid-cols-4 mb-6">
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("fromGodown")}</CardTitle></CardHeader>
          <CardContent className="text-lg font-bold">{(transfer.from_godown as any)?.name}</CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("toGodown")}</CardTitle></CardHeader>
          <CardContent className="text-lg font-bold">{(transfer.to_godown as any)?.name}</CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("date")}</CardTitle></CardHeader>
          <CardContent className="text-lg font-bold">{new Date(transfer.transfer_date).toLocaleDateString()}</CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{tr("status")}</CardTitle></CardHeader>
          <CardContent><Badge variant={statusColor(transfer.status) as any} className="text-sm">{tr(transfer.status)}</Badge></CardContent>
        </Card>
      </div>

      {/* Actions */}
      {transfer.status === "pending" && isAdmin && (
        <div className="flex gap-2 mb-6">
          <Button onClick={() => approveMutation.mutate()} disabled={approveMutation.isPending}>
            <CheckCircle className="mr-2 h-4 w-4" />
            {approveMutation.isPending ? tr("saving") : tr("approveTransfer")}
          </Button>
          <Button variant="destructive" onClick={() => cancelMutation.mutate()} disabled={cancelMutation.isPending}>
            <XCircle className="mr-2 h-4 w-4" />
            {tr("cancelTransfer")}
          </Button>
        </div>
      )}

      {transfer.note && (
        <p className="text-sm text-muted-foreground mb-4"><strong>{tr("note")}:</strong> {transfer.note}</p>
      )}

      {/* Items */}
      <div className="rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>#</TableHead>
              <TableHead>{tr("productName")}</TableHead>
              <TableHead>{tr("sku")}</TableHead>
              <TableHead>{tr("quantity")}</TableHead>
              <TableHead>{tr("unit")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.map((item: any, idx: number) => (
              <TableRow key={item.id}>
                <TableCell>{idx + 1}</TableCell>
                <TableCell className="font-medium">{item.products?.name || "—"}</TableCell>
                <TableCell>{item.products?.sku || "—"}</TableCell>
                <TableCell>{item.quantity}</TableCell>
                <TableCell>{item.unit}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </PageLayout>
  );
}
