import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Search, Eye } from "lucide-react";
import { useState } from "react";

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

function TransferListPage() {
  const { tr } = useLanguage();
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

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

  const filtered = transfers.filter((t: any) => {
    const matchSearch = t.transfer_no.toLowerCase().includes(search.toLowerCase()) ||
      (t.from_godown as any)?.name?.toLowerCase().includes(search.toLowerCase()) ||
      (t.to_godown as any)?.name?.toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === "all" || t.status === statusFilter;
    return matchSearch && matchStatus;
  });

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

  return (
    <PageLayout title={tr("transferList")} subtitle={tr("stockTransferSubtitle")}>
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex gap-2 items-center">
          <div className="relative max-w-xs">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input placeholder={tr("search")} value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-36"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{tr("all")}</SelectItem>
              <SelectItem value="pending">{tr("pending")}</SelectItem>
              <SelectItem value="approved">{tr("approved")}</SelectItem>
              <SelectItem value="cancelled">{tr("cancelled")}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <Link to="/transfers/create">
          <Button><Plus className="mr-2 h-4 w-4" />{tr("createTransfer")}</Button>
        </Link>
      </div>

      <div className="mt-4 rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{tr("transferNo")}</TableHead>
              <TableHead>{tr("fromGodown")}</TableHead>
              <TableHead>{tr("toGodown")}</TableHead>
              <TableHead>{tr("totalItems")}</TableHead>
              <TableHead>{tr("date")}</TableHead>
              <TableHead>{tr("status")}</TableHead>
              <TableHead className="text-right">{tr("action")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">{tr("loading")}</TableCell></TableRow>
            ) : filtered.length === 0 ? (
              <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">{tr("noData")}</TableCell></TableRow>
            ) : (
              filtered.map((t: any) => (
                <TableRow key={t.id}>
                  <TableCell className="font-mono font-medium">{t.transfer_no}</TableCell>
                  <TableCell>{(t.from_godown as any)?.name || "—"}</TableCell>
                  <TableCell>{(t.to_godown as any)?.name || "—"}</TableCell>
                  <TableCell>{t.total_items}</TableCell>
                  <TableCell>{new Date(t.transfer_date).toLocaleDateString()}</TableCell>
                  <TableCell>
                    <Badge variant={statusColor(t.status) as any}>
                      {tr(t.status)}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <Link to="/transfers/$transferId" params={{ transferId: t.id }}>
                      <Button variant="ghost" size="icon"><Eye className="h-4 w-4" /></Button>
                    </Link>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </PageLayout>
  );
}
