"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { BarcodeListTable } from "@/components/barcode/BarcodeListTable";
import { BarcodeScanModal } from "@/components/common/BarcodeScanModal";
import { Plus, Search, RotateCcw, Scan } from "lucide-react";
import { useBarcodeList } from "@/hooks/useBarcodeList";

export default function BarcodeLabelManagementPage() {
  const router = useRouter();
  const [searchText, setSearchText] = useState("");
  const [scanModalOpen, setScanModalOpen] = useState(false);
  const [scannedBarcode, setScannedBarcode] = useState<string | null>(null);

  const { labels, total, page, limit, isLoading, refetch, setPage, handleSearch } = useBarcodeList();

  const handleSearchClick = () => {
    handleSearch(searchText);
  };

  const handleReset = () => {
    setSearchText("");
    handleSearch("");
  };

  const handleCreateNew = () => {
    router.push("/admin/screenMng/barcodeList/designer/new");
  };

  return (
    <div className="min-h-screen bg-muted">
      <div className="w-full max-w-none space-y-8 px-4 py-8">
        <div className="flex items-center justify-between rounded-lg border bg-white p-6 shadow-sm">
          <div>
            <h1 className="text-3xl font-bold text-foreground">바코드 라벨 관리</h1>
            <p className="mt-2 text-muted-foreground">ZD421 등 바코드 프린터용 라벨을 작성하고 출력합니다</p>
          </div>
          <Button onClick={handleCreateNew} className="gap-2">
            <Plus className="h-4 w-4" />
            새 라벨
          </Button>
        </div>

        <Card className="shadow-sm">
          <CardHeader className="bg-muted/50">
            <CardTitle className="flex items-center gap-2">
              <Search className="h-5 w-5" />
              검색
            </CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="flex gap-2">
              <Input
                placeholder="라벨명으로 검색..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    handleSearchClick();
                  }
                }}
                className="flex-1"
              />
              <Button onClick={handleSearchClick} className="gap-2">
                <Search className="h-4 w-4" />
                검색
              </Button>
              <Button onClick={handleReset} variant="outline" className="gap-2">
                <RotateCcw className="h-4 w-4" />
                초기화
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* 카메라 스캔: 바코드 값을 텍스트로 추출해 표시 */}
        <Card className="shadow-sm">
          <CardHeader className="bg-gray-50/50">
            <CardTitle className="flex items-center gap-2">
              <Scan className="h-5 w-5" />
              바코드 스캔
            </CardTitle>
            <p className="text-muted-foreground text-sm">
              카메라로 바코드를 스캔하면 추출된 값을 아래에 텍스트로 표시합니다.
            </p>
          </CardHeader>
          <CardContent className="space-y-4">
            <Button onClick={() => setScanModalOpen(true)} variant="outline" className="gap-2">
              <Scan className="h-4 w-4" />
              카메라로 바코드 스캔
            </Button>
            {scannedBarcode ? (
              <div className="rounded-lg border bg-muted/30 p-4">
                <p className="text-muted-foreground mb-1 text-sm">추출된 바코드 값</p>
                <p className="font-mono text-lg font-semibold break-all">{scannedBarcode}</p>
              </div>
            ) : (
              <p className="text-muted-foreground text-sm">아직 스캔한 바코드가 없습니다. 위 버튼으로 스캔해 보세요.</p>
            )}
          </CardContent>
        </Card>

        <Card className="shadow-sm">
          <CardHeader className="bg-muted/50">
            <CardTitle className="flex items-center justify-between">
              <span className="flex items-center gap-2">
                바코드 라벨 목록
                <span className="text-muted-foreground text-sm font-normal">(총 {total}건)</span>
              </span>
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <BarcodeListTable
              labels={labels}
              total={total}
              page={page}
              limit={limit}
              isLoading={isLoading}
              onPageChange={setPage}
              onRefresh={refetch}
            />
          </CardContent>
        </Card>

        <BarcodeScanModal
          open={scanModalOpen}
          onOpenChange={setScanModalOpen}
          targetField="바코드 값"
          barcodeFormat="all"
          autoSubmit={false}
          onScanSuccess={(barcode) => {
            setScannedBarcode(barcode);
            setScanModalOpen(false);
          }}
        />
      </div>
    </div>
  );
}
