"use client";

import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { ArrowLeft, Building2, CheckCircle2, CreditCard } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate, formatDateTime } from "@/shared/lib/format-date";
import {
  RFID_BATCH_STATUS_COLORS as statusColors,
  RFID_CHANGE_TYPE_COLORS as changeColors,
} from "@/shared/constants/status-colors";
import ConfirmationDialog from "@/presentation/components/shared/confirmation-dialog";
import { Button } from "@/presentation/components/ui/button";
import { Badge } from "@/presentation/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import type { RfidCardBatchDetail, RfidChangeType } from "@/domain/entities/rfid-card-batch";

export default function RfidBatchDetailPage() {
  const t = useT();
  const locale = useLocale();
  usePageHeader(t.pages.rfidBatchDetail.title, t.pages.rfidBatchDetail.subtitle);
  const params = useParams();
  const router = useRouter();
  const container = useRepositories();
  const batchId = Number(params.id);
  const [processOpen, setProcessOpen] = useState(false);

  const { data: batch, loading, refetch } = useApiQuery(
    () => container.rfidCardBatchRepository.findById(batchId),
    { deps: [batchId], enabled: !!batchId }
  );

  const processMutation = useApiMutation<void, RfidCardBatchDetail>(
    () => container.rfidCardBatchRepository.process(batchId),
    {
      successMessage: t.rfid.toasts.processed,
      onSuccess: () => {
        setProcessOpen(false);
        refetch();
      },
    }
  );

  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-8 w-48" />
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2">
            <Skeleton className="h-64 rounded-xl" />
          </div>
          <Skeleton className="h-64 rounded-xl" />
        </div>
      </div>
    );
  }

  if (!batch) {
    return (
      <div className="p-6">
        <div className="flex items-center justify-center h-48 rounded-xl border border-dashed border-border">
          <p className="text-sm text-muted-foreground">{t.rfid.detail.notFound}</p>
        </div>
      </div>
    );
  }

  const isProcessing = batch.status === "processing";
  const changeTypeLabel = (ct: RfidChangeType) => t.rfid.detail.changeTypes[ct] ?? ct;

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => router.push("/cartes-rfid")}>
            <ArrowLeft className="w-4 h-4" />
          </Button>
          <div>
            <h2 className="text-lg font-bold text-foreground">
              {t.rfid.detail.referenceLabel(batch.reference)}
            </h2>
            <p className="text-xs text-muted-foreground">{batch.company?.name}</p>
          </div>
        </div>
        {isProcessing && (
          <Button size="sm" onClick={() => setProcessOpen(true)}>
            <CheckCircle2 className="w-4 h-4 mr-1" />
            {t.rfid.detail.process.button}
          </Button>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Changes */}
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">
                {t.rfid.detail.sections.changes(batch.changes.length)}
              </CardTitle>
            </CardHeader>
            <CardContent>
              {batch.changes.length === 0 ? (
                <p className="py-8 text-center text-sm text-muted-foreground">
                  {t.rfid.detail.change.empty}
                </p>
              ) : (
                <div className="space-y-3">
                  {batch.changes.map((c) => (
                    <div key={c.id} className="rounded-lg border border-border p-3">
                      <div className="flex items-center justify-between gap-3">
                        <Badge className={`${changeColors[c.change_type] ?? ""} border-0 text-xs`}>
                          {changeTypeLabel(c.change_type)}
                        </Badge>
                        {c.card && (
                          <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                            <CreditCard className="w-3 h-3" />
                            {t.rfid.detail.change.card(c.card.public_number)}
                          </span>
                        )}
                      </div>
                      <p className="mt-2 text-sm whitespace-pre-wrap break-words">{c.summary}</p>
                      <div className="mt-1.5 flex flex-wrap gap-x-4 gap-y-0.5 text-xs text-muted-foreground">
                        {c.requested_by && (
                          <span>
                            {t.rfid.detail.change.requestedBy}: {c.requested_by}
                          </span>
                        )}
                        {c.created_at && <span>{formatDate(c.created_at, locale)}</span>}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Info sidebar */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">{t.rfid.detail.sections.info}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <InfoRow label={t.rfid.detail.fields.status}>
                <Badge className={`${statusColors[batch.status] ?? ""} border-0 text-xs`}>
                  {batch.status_label}
                </Badge>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.company}>
                <span className="inline-flex items-center gap-2 text-sm">
                  <Building2 className="w-4 h-4 text-muted-foreground" />
                  {batch.company?.name}
                </span>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.changesCount}>
                <span className="text-sm tabular-nums">{batch.changes_count}</span>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.submittedBy}>
                <span className="text-sm">{batch.submitted_by ?? t.rfid.detail.fields.empty}</span>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.submittedAt}>
                <span className="text-sm">
                  {batch.submitted_at ? formatDateTime(batch.submitted_at, locale) : t.rfid.detail.fields.empty}
                </span>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.processedBy}>
                <span className="text-sm">{batch.processed_by ?? t.rfid.detail.fields.empty}</span>
              </InfoRow>
              <InfoRow label={t.rfid.detail.fields.processedAt}>
                <span className="text-sm">
                  {batch.processed_at ? formatDateTime(batch.processed_at, locale) : t.rfid.detail.fields.empty}
                </span>
              </InfoRow>
            </CardContent>
          </Card>
        </div>
      </div>

      <ConfirmationDialog
        open={processOpen}
        onOpenChange={setProcessOpen}
        title={t.rfid.detail.process.confirmTitle}
        description={t.rfid.detail.process.confirmDescription}
        confirmLabel={t.rfid.detail.process.button}
        loading={processMutation.loading}
        onConfirm={() => processMutation.mutate()}
      />
    </div>
  );
}

function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <p className="text-xs font-semibold text-muted-foreground mb-1.5">{label}</p>
      {children}
    </div>
  );
}
