"use client";

import { useTransition } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Container } from "@/components/container";
import { useLanguage } from "@/lib/i18n/context";
import { toggleDataSourceAction } from "@/actions/admin-import-actions";

export interface DataSourceRow {
  id: string;
  code: string;
  name: string;
  type: string;
  isActive: boolean;
  isDemo: boolean;
  lastSuccessfulSyncAt: Date | null;
}

function DataSourceRowItem({ source }: { source: DataSourceRow }) {
  const { t, locale } = useLanguage();
  const ds = t.admin.dataSources;
  const [isPending, startTransition] = useTransition();

  function handleToggle() {
    startTransition(async () => {
      const result = await toggleDataSourceAction(source.id, !source.isActive, locale);
      if (!result.success) toast.error(result.error);
    });
  }

  return (
    <tr className="border-b border-border last:border-0">
      <td className="whitespace-nowrap p-3 font-mono text-xs text-foreground">{source.code}</td>
      <td className="truncate p-3 text-foreground">{source.name}</td>
      <td className="whitespace-nowrap p-3 text-muted-foreground">{source.type}</td>
      <td className="whitespace-nowrap p-3">
        <div className="flex flex-wrap items-center gap-1.5">
          <Badge variant={source.isActive ? "default" : "outline"}>
            {source.isActive ? ds.active : t.admin.products.inactive}
          </Badge>
          {source.isDemo && <Badge variant="outline">{ds.demo}</Badge>}
        </div>
      </td>
      <td className="whitespace-nowrap p-3 text-muted-foreground">
        {source.lastSuccessfulSyncAt
          ? new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", {
              year: "numeric",
              month: "short",
              day: "numeric",
            }).format(source.lastSuccessfulSyncAt)
          : ds.never}
      </td>
      <td className="whitespace-nowrap p-3 text-right">
        <Button size="sm" variant="outline" onClick={handleToggle} disabled={isPending}>
          {source.isActive ? ds.disable : ds.enable}
        </Button>
      </td>
    </tr>
  );
}

export function AdminDataSourcesContent({ sources }: { sources: DataSourceRow[] }) {
  const { t } = useLanguage();
  const ds = t.admin.dataSources;

  return (
    <div className="admin-page py-8">
      <Container className="flex flex-col gap-4">
        <h1 className="admin-page-intro text-lg font-semibold text-foreground">{ds.title}</h1>
        <div className="admin-table-frame overflow-x-auto">
          <table className="admin-data-table w-full min-w-[760px] table-fixed text-left text-sm">
            <colgroup>
              <col style={{ width: "17%" }} />
              <col style={{ width: "25%" }} />
              <col style={{ width: "15%" }} />
              <col style={{ width: "18%" }} />
              <col style={{ width: "15%" }} />
              <col style={{ width: "10%" }} />
            </colgroup>
            <thead>
              <tr className="border-b border-border text-xs text-muted-foreground">
                <th scope="col" className="whitespace-nowrap p-3 font-medium">
                  {ds.code}
                </th>
                <th scope="col" className="whitespace-nowrap p-3 font-medium">
                  {ds.name}
                </th>
                <th scope="col" className="whitespace-nowrap p-3 font-medium">
                  {ds.type}
                </th>
                <th scope="col" className="whitespace-nowrap p-3 font-medium">
                  {ds.active}
                </th>
                <th scope="col" className="whitespace-nowrap p-3 font-medium">
                  {ds.lastSync}
                </th>
                <th scope="col" className="p-3 font-medium" />
              </tr>
            </thead>
            <tbody>
              {sources.map((source) => (
                <DataSourceRowItem key={source.id} source={source} />
              ))}
            </tbody>
          </table>
        </div>
      </Container>
    </div>
  );
}
