"use client";

import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import * as XLSX from "xlsx";
import { trpc } from "@/trpc/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface ImportRow {
  code?: string;
  name: string;
  description?: string;
  unit: string;
  categoryCode: string;
  rate?: number;
  defaultWeight?: number;
  error?: string;
}

export default function BulkImportPage() {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [rows, setRows] = useState<ImportRow[]>([]);
  const [fiscalYearId, setFiscalYearId] = useState("");
  const [importing, setImporting] = useState(false);
  const [results, setResults] = useState<{
    created: number;
    updated: number;
    errors: string[];
  } | null>(null);

  const { data: categories } = trpc.category.getAll.useQuery();
  const { data: fiscalYears } = trpc.settings.getFiscalYears.useQuery();
  const { data: activeFiscalYear } =
    trpc.settings.getActiveFiscalYear.useQuery();

  useEffect(() => {
    if (activeFiscalYear?.id && !fiscalYearId) {
      setFiscalYearId(activeFiscalYear.id);
    }
  }, [activeFiscalYear]);

  const importMutation = trpc.item.importBulk.useMutation({
    onSuccess: (data) => {
      setResults(data);
      setImporting(false);
    },
    onError: () => {
      setImporting(false);
    },
  });

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const data = await file.arrayBuffer();
    const workbook = XLSX.read(data);
    const sheetName = workbook.SheetNames[0];
    if (!sheetName) return;
    const sheet = workbook.Sheets[sheetName];
    if (!sheet) return;
    const json: Record<string, unknown>[] = XLSX.utils.sheet_to_json(sheet);

    const parsed: ImportRow[] = json.map((row) => ({
      code: row.code ? String(row.code as string) : undefined,
      name: String((row.name as string) ?? ""),
      description: row.description
        ? String(row.description as string)
        : undefined,
      unit: String((row.unit as string) ?? ""),
      categoryCode: String((row.categoryCode as string) ?? ""),
      rate: row.rate ? Number(row.rate) : undefined,
      defaultWeight: row.defaultWeight ? Number(row.defaultWeight) : undefined,
    }));

    setRows(parsed);
  };

  const handleImport = () => {
    if (!fiscalYearId || rows.length === 0) return;
    setImporting(true);
    importMutation.mutate({ data: rows, fiscalYearId });
  };

  const downloadTemplate = () => {
    const template = [
      {
        code: "ITM-001",
        name: "Example Item",
        description: "Description",
        unit: "pcs",
        categoryCode: "BRIDGE",
        rate: 100,
        defaultWeight: 1.0,
      },
    ];
    const ws = XLSX.utils.json_to_sheet(template);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Template");
    XLSX.writeFile(wb, "items_import_template.xlsx");
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <Button variant="ghost" onClick={() => router.push("/items")}>
            ← Back to Items
          </Button>
          <h1 className="mt-2 text-3xl font-bold">Bulk Import Items</h1>
        </div>
        <Button variant="outline" onClick={downloadTemplate}>
          Download Template
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Upload File</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label>Fiscal Year (for rates)</Label>
            <select
              className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus:ring-ring flex h-10 w-full items-center justify-between rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
              value={fiscalYearId}
              onChange={(e) => setFiscalYearId(e.target.value)}
            >
              <option value="">Select fiscal year</option>
              {fiscalYears?.map((fy) => (
                <option key={fy.id} value={fy.id}>
                  {fy.year}
                  {fy.isActive ? " (Active)" : ""}
                </option>
              ))}
            </select>
          </div>
          <div>
            <Label>Excel/CSV File</Label>
            <Input
              ref={fileInputRef}
              type="file"
              accept=".xlsx,.xls,.csv"
              onChange={handleFileUpload}
            />
          </div>
        </CardContent>
      </Card>

      {rows.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Preview ({rows.length} rows)</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Code</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Unit</TableHead>
                  <TableHead>Category</TableHead>
                  <TableHead>Rate</TableHead>
                  <TableHead>Weight</TableHead>
                  <TableHead>Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.slice(0, 10).map((row, i) => {
                  const category = categories?.find(
                    (c) => c.code === row.categoryCode,
                  );
                  return (
                    <TableRow key={i}>
                      <TableCell>{row.code || "(auto)"}</TableCell>
                      <TableCell>{row.name}</TableCell>
                      <TableCell>{row.unit}</TableCell>
                      <TableCell>
                        {category?.name || row.categoryCode}
                      </TableCell>
                      <TableCell>{row.rate || "-"}</TableCell>
                      <TableCell>{row.defaultWeight ?? "-"}</TableCell>
                      <TableCell>{category ? "✓" : "✗ Missing"}</TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
            {rows.length > 10 && (
              <p className="text-muted-foreground mt-2">
                ...and {rows.length - 10} more rows
              </p>
            )}
            <Button
              className="mt-4"
              onClick={handleImport}
              disabled={importing || !fiscalYearId}
            >
              {importing ? "Importing..." : "Import Items"}
            </Button>
          </CardContent>
        </Card>
      )}

      {results && (
        <Card>
          <CardHeader>
            <CardTitle>Import Results</CardTitle>
          </CardHeader>
          <CardContent>
            <p>Created: {results.created}</p>
            <p>Updated: {results.updated}</p>
            {results.errors.length > 0 && (
              <div className="mt-2">
                <p className="font-semibold">Errors:</p>
                <ul className="list-disc pl-4">
                  {results.errors.map((err, i) => (
                    <li key={i}>{err}</li>
                  ))}
                </ul>
              </div>
            )}
            <Button className="mt-4" onClick={() => router.push("/items")}>
              View Items
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
