"use client";

import { useRef, useTransition } from "react";
import { Loader2, UploadCloud } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Container } from "@/components/container";
import { useLanguage } from "@/lib/i18n/context";
import { importJsonAction, importCsvAction } from "@/actions/admin-import-actions";
import type { Locale } from "@/lib/i18n/translations";
import type { ActionResult } from "@/types/actions";

export interface ImportJobRow {
  id: string;
  status: string;
  filename: string | null;
  totalRows: number;
  createdCount: number;
  updatedCount: number;
  skippedCount: number;
  failedCount: number;
  sourceCode: string;
  createdAt: Date;
}

function ImportForm({
  title,
  description,
  action,
  accept,
}: {
  title: string;
  description: string;
  action: (formData: FormData, locale: Locale) => Promise<ActionResult>;
  accept: string;
}) {
  const { t, locale } = useLanguage();
  const a = t.admin.imports;
  const formRef = useRef<HTMLFormElement>(null);
  const [isPending, startTransition] = useTransition();

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    startTransition(async () => {
      const result = await action(formData, locale);
      if (result.success) {
        toast.success(result.message ?? a.success);
        formRef.current?.reset();
      } else {
        toast.error(result.error);
      }
    });
  }

  return (
    <Card className="admin-surface">
      <CardHeader>
        <CardTitle>{title}</CardTitle>
        <CardDescription>{description}</CardDescription>
      </CardHeader>
      <CardContent>
        <form ref={formRef} onSubmit={handleSubmit} className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <input
            type="file"
            name="file"
            accept={accept}
            required
            aria-label={a.uploadFile}
            className="text-sm text-muted-foreground file:mr-3 file:rounded-lg file:border-0 file:bg-secondary file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-foreground"
          />
          <Button type="submit" disabled={isPending} size="sm">
            {isPending ? <Loader2 className="size-4 animate-spin" /> : <UploadCloud className="size-4" />}
            {a.submit}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}

export function AdminImportsContent({ jobs }: { jobs: ImportJobRow[] }) {
  const { t } = useLanguage();
  const a = t.admin.imports;

  return (
    <div className="py-8">
      <Container className="flex flex-col gap-6">
        <div className="grid gap-4 md:grid-cols-2">
          <ImportForm title={a.jsonTitle} description={a.jsonDescription} action={importJsonAction} accept="application/json" />
          <ImportForm title={a.csvTitle} description={a.csvDescription} action={importCsvAction} accept=".csv,text/csv" />
        </div>

        <div className="flex flex-col gap-3">
          <h2 className="text-sm font-semibold text-foreground">{a.recentJobs}</h2>
          <div className="admin-table-frame overflow-x-auto">
            <table className="admin-data-table w-full min-w-[640px] table-fixed text-left text-sm">
              <colgroup>
                <col style={{ width: "22%" }} />
                <col style={{ width: "15.6%" }} />
                <col style={{ width: "15.6%" }} />
                <col style={{ width: "15.6%" }} />
                <col style={{ width: "15.6%" }} />
                <col style={{ width: "15.6%" }} />
              </colgroup>
              <thead>
                <tr className="border-b border-border text-xs text-muted-foreground">
                  <th scope="col" className="whitespace-nowrap p-3 font-medium">
                    {a.status}
                  </th>
                  <th scope="col" className="whitespace-nowrap p-3 text-right font-medium">
                    {a.rows}
                  </th>
                  <th scope="col" className="whitespace-nowrap p-3 text-right font-medium">
                    {a.created}
                  </th>
                  <th scope="col" className="whitespace-nowrap p-3 text-right font-medium">
                    {a.updated}
                  </th>
                  <th scope="col" className="whitespace-nowrap p-3 text-right font-medium">
                    {a.skipped}
                  </th>
                  <th scope="col" className="whitespace-nowrap p-3 text-right font-medium">
                    {a.failed}
                  </th>
                </tr>
              </thead>
              <tbody>
                {jobs.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="p-3 text-center text-muted-foreground">
                      —
                    </td>
                  </tr>
                ) : (
                  jobs.map((job) => (
                    <tr key={job.id} className="border-b border-border last:border-0">
                      <td className="p-3">
                        <Badge variant="outline">{job.status}</Badge>
                      </td>
                      <td className="whitespace-nowrap p-3 text-right tabular-nums text-foreground">{job.totalRows}</td>
                      <td className="whitespace-nowrap p-3 text-right tabular-nums text-foreground">{job.createdCount}</td>
                      <td className="whitespace-nowrap p-3 text-right tabular-nums text-foreground">{job.updatedCount}</td>
                      <td className="whitespace-nowrap p-3 text-right tabular-nums text-foreground">{job.skippedCount}</td>
                      <td className="whitespace-nowrap p-3 text-right tabular-nums text-foreground">{job.failedCount}</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </Container>
    </div>
  );
}
