import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "./ui/dialog";
import { Textarea } from "./ui/textarea";
import { toast } from "sonner@2.0.3";
import {
  Package,
  PackageCheck,
  PackageMinus,
  Plus,
  Search,
  Filter,
  Download,
  Upload,
  TrendingDown,
  TrendingUp,
  ArrowUpCircle,
  ArrowDownCircle,
  BarChart3,
  CalendarDays,
  User,
  FileText,
  X,
  Edit,
  Trash2,
  Eye
} from "lucide-react";

interface InventoryTransaction {
  id: string;
  date: string;
  type: "입고" | "출고";
  documentNo: string;
  itemCode: string;
  itemName: string;
  spec: string;
  unit: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  warehouse: string;
  location: string;
  supplier?: string;
  customer?: string;
  department?: string;
  purpose?: string;
  requestBy: string;
  approvedBy?: string;
  status: "대기" | "승인" | "완료" | "취소";
  remarks?: string;
}

export function InventoryManagement() {
  const [activeTab, setActiveTab] = useState<"incoming" | "outgoing" | "history">("incoming");
  const [showWriteDialog, setShowWriteDialog] = useState(false);
  const [transactionType, setTransactionType] = useState<"입고" | "출고">("입고");
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [selectedTransaction, setSelectedTransaction] = useState<InventoryTransaction | null>(null);
  const [showDetailDialog, setShowDetailDialog] = useState(false);

  // 입출고 거래 데이터
  const [transactions, setTransactions] = useState<InventoryTransaction[]>([
    {
      id: "IN-2025-001",
      date: "2025-01-15",
      type: "입고",
      documentNo: "PO-2025-001",
      itemCode: "RM-001",
      itemName: "EGIT-SST",
      spec: "1219*3500",
      unit: "장",
      quantity: 80,
      unitPrice: 52000,
      totalPrice: 4160000,
      warehouse: "1공장 창고",
      location: "A-01",
      supplier: "지프하스",
      requestBy: "김입고",
      approvedBy: "이관리",
      status: "완료",
      remarks: "정상 입고"
    },
    {
      id: "OUT-2025-001",
      date: "2025-01-16",
      type: "출고",
      documentNo: "WO-2025-001",
      itemCode: "RM-001",
      itemName: "EGIT-SST",
      spec: "1219*3500",
      unit: "장",
      quantity: 30,
      unitPrice: 52000,
      totalPrice: 1560000,
      warehouse: "1공장 창고",
      location: "A-01",
      department: "생산1팀",
      purpose: "생산 투입",
      requestBy: "박생산",
      approvedBy: "이관리",
      status: "완료",
      remarks: ""
    },
    {
      id: "IN-2025-002",
      date: "2025-01-17",
      type: "입고",
      documentNo: "PO-2025-002",
      itemCode: "RM-002",
      itemName: "철판",
      spec: "2000*4000*3.0T",
      unit: "장",
      quantity: 50,
      unitPrice: 85000,
      totalPrice: 4250000,
      warehouse: "1공장 창고",
      location: "B-05",
      supplier: "현대제철",
      requestBy: "최구매",
      status: "승인",
      remarks: "검수 대기"
    },
    {
      id: "OUT-2025-002",
      date: "2025-01-18",
      type: "출고",
      documentNo: "WO-2025-002",
      itemCode: "RM-003",
      itemName: "볼트 M10",
      spec: "M10*30",
      unit: "개",
      quantity: 500,
      unitPrice: 150,
      totalPrice: 75000,
      warehouse: "부자재 창고",
      location: "C-12",
      department: "조립팀",
      purpose: "조립 작업",
      requestBy: "정조립",
      status: "대기",
      remarks: "긴급"
    }
  ]);

  const [formData, setFormData] = useState<Partial<InventoryTransaction>>({
    type: "입고",
    date: new Date().toISOString().split('T')[0],
    warehouse: "1공장 창고",
    status: "대기",
    unit: "장",
    quantity: 0,
    unitPrice: 0,
    totalPrice: 0
  });

  // 필터링된 거래
  const getFilteredTransactions = () => {
    let filtered = transactions;

    if (activeTab === "incoming") {
      filtered = filtered.filter(t => t.type === "입고");
    } else if (activeTab === "outgoing") {
      filtered = filtered.filter(t => t.type === "출고");
    }

    if (filterStatus !== "all") {
      filtered = filtered.filter(t => t.status === filterStatus);
    }

    if (searchTerm) {
      filtered = filtered.filter(t =>
        t.itemName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        t.documentNo.toLowerCase().includes(searchTerm.toLowerCase()) ||
        t.itemCode.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    return filtered;
  };

  // 통계 계산
  const getStats = () => {
    const today = new Date().toISOString().split('T')[0];
    const thisMonth = today.substring(0, 7);

    const todayIncoming = transactions.filter(t => t.type === "입고" && t.date === today && t.status === "완료");
    const todayOutgoing = transactions.filter(t => t.type === "출고" && t.date === today && t.status === "완료");
    const monthIncoming = transactions.filter(t => t.type === "입고" && t.date.startsWith(thisMonth) && t.status === "완료");
    const monthOutgoing = transactions.filter(t => t.type === "출고" && t.date.startsWith(thisMonth) && t.status === "완료");
    const pending = transactions.filter(t => t.status === "대기");

    return {
      todayIncoming: todayIncoming.reduce((sum, t) => sum + t.totalPrice, 0),
      todayOutgoing: todayOutgoing.reduce((sum, t) => sum + t.totalPrice, 0),
      monthIncoming: monthIncoming.reduce((sum, t) => sum + t.totalPrice, 0),
      monthOutgoing: monthOutgoing.reduce((sum, t) => sum + t.totalPrice, 0),
      pendingCount: pending.length
    };
  };

  const stats = getStats();

  // 입출고 등록
  const handleSubmit = () => {
    if (!formData.itemCode || !formData.itemName || !formData.quantity) {
      toast.error("필수 항목을 입력해주세요.");
      return;
    }

    const newTransaction: InventoryTransaction = {
      id: `${formData.type === "입고" ? "IN" : "OUT"}-2025-${String(transactions.length + 1).padStart(3, '0')}`,
      date: formData.date!,
      type: formData.type as "입고" | "출고",
      documentNo: formData.documentNo || "-",
      itemCode: formData.itemCode!,
      itemName: formData.itemName!,
      spec: formData.spec || "-",
      unit: formData.unit!,
      quantity: formData.quantity!,
      unitPrice: formData.unitPrice!,
      totalPrice: formData.quantity! * formData.unitPrice!,
      warehouse: formData.warehouse!,
      location: formData.location || "-",
      supplier: formData.supplier,
      customer: formData.customer,
      department: formData.department,
      purpose: formData.purpose,
      requestBy: formData.requestBy || "현재사용자",
      status: "대기",
      remarks: formData.remarks
    };

    setTransactions([newTransaction, ...transactions]);
    toast.success(`${formData.type} 요청이 등록되었습니다.`);
    setShowWriteDialog(false);
    resetForm();
  };

  const resetForm = () => {
    setFormData({
      type: transactionType,
      date: new Date().toISOString().split('T')[0],
      warehouse: "1공장 창고",
      status: "대기",
      unit: "장",
      quantity: 0,
      unitPrice: 0,
      totalPrice: 0
    });
  };

  // 상태 변경
  const updateStatus = (id: string, status: InventoryTransaction["status"]) => {
    setTransactions(transactions.map(t =>
      t.id === id ? { ...t, status, approvedBy: status === "승인" || status === "완료" ? "이관리" : t.approvedBy } : t
    ));
    toast.success(`상태가 ${status}(으)로 변경되었습니다.`);
  };

  // 상태 뱃지 색상
  const getStatusColor = (status: string) => {
    switch (status) {
      case "완료": return "bg-green-600";
      case "승인": return "bg-blue-600";
      case "대기": return "bg-yellow-600";
      case "취소": return "bg-red-600";
      default: return "bg-gray-600";
    }
  };

  return (
    <div className="p-3 md:p-6 space-y-4 md:space-y-6 bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen">
      {/* 헤더 */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
        <div>
          <h1 className="text-xl md:text-3xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">
            입/출고 관리
          </h1>
          <p className="text-xs md:text-sm text-muted-foreground mt-1">
            자재 입출고 현황 및 재고 이동 관리
          </p>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 md:gap-4">
        <Card className="border-0 shadow-lg bg-gradient-to-br from-blue-500 to-blue-600 text-white">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs opacity-90">오늘 입고</p>
                <p className="text-xl md:text-2xl font-bold mt-1">
                  {(stats.todayIncoming / 10000).toFixed(0)}만원
                </p>
              </div>
              <ArrowDownCircle className="h-8 w-8 opacity-80" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-lg bg-gradient-to-br from-purple-500 to-purple-600 text-white">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs opacity-90">오늘 출고</p>
                <p className="text-xl md:text-2xl font-bold mt-1">
                  {(stats.todayOutgoing / 10000).toFixed(0)}만원
                </p>
              </div>
              <ArrowUpCircle className="h-8 w-8 opacity-80" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-lg bg-gradient-to-br from-green-500 to-green-600 text-white">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs opacity-90">월 입고</p>
                <p className="text-xl md:text-2xl font-bold mt-1">
                  {(stats.monthIncoming / 10000).toFixed(0)}만원
                </p>
              </div>
              <TrendingDown className="h-8 w-8 opacity-80" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-lg bg-gradient-to-br from-orange-500 to-orange-600 text-white">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs opacity-90">월 출고</p>
                <p className="text-xl md:text-2xl font-bold mt-1">
                  {(stats.monthOutgoing / 10000).toFixed(0)}만원
                </p>
              </div>
              <TrendingUp className="h-8 w-8 opacity-80" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-lg bg-gradient-to-br from-yellow-500 to-yellow-600 text-white">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs opacity-90">승인 대기</p>
                <p className="text-xl md:text-2xl font-bold mt-1">
                  {stats.pendingCount}건
                </p>
              </div>
              <BarChart3 className="h-8 w-8 opacity-80" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 메인 컨텐츠 */}
      <Card className="border-0 shadow-lg">
        <CardHeader>
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
            <CardTitle>입출고 현황</CardTitle>
            <div className="flex flex-wrap gap-2 w-full sm:w-auto">
              <Button
                onClick={() => {
                  setTransactionType("입고");
                  setFormData({ ...formData, type: "입고" });
                  setShowWriteDialog(true);
                }}
                className="flex-1 sm:flex-none rounded-xl shadow-md bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700"
              >
                <ArrowDownCircle className="h-4 w-4 mr-2" />
                입고 등록
              </Button>
              <Button
                onClick={() => {
                  setTransactionType("출고");
                  setFormData({ ...formData, type: "출고" });
                  setShowWriteDialog(true);
                }}
                variant="outline"
                className="flex-1 sm:flex-none rounded-xl"
              >
                <ArrowUpCircle className="h-4 w-4 mr-2" />
                출고 등록
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 탭 & 검색 필터 */}
          <div className="flex flex-col lg:flex-row gap-3">
            <div className="flex gap-2">
              <Button
                variant={activeTab === "incoming" ? "default" : "outline"}
                onClick={() => setActiveTab("incoming")}
                className="flex-1"
              >
                <PackageCheck className="h-4 w-4 mr-2" />
                입고
              </Button>
              <Button
                variant={activeTab === "outgoing" ? "default" : "outline"}
                onClick={() => setActiveTab("outgoing")}
                className="flex-1"
              >
                <PackageMinus className="h-4 w-4 mr-2" />
                출고
              </Button>
              <Button
                variant={activeTab === "history" ? "default" : "outline"}
                onClick={() => setActiveTab("history")}
                className="flex-1"
              >
                <FileText className="h-4 w-4 mr-2" />
                전체
              </Button>
            </div>

            <div className="flex gap-2 flex-1">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="품목명, 문서번호, 품목코드 검색..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체 상태</SelectItem>
                  <SelectItem value="대기">대기</SelectItem>
                  <SelectItem value="승인">승인</SelectItem>
                  <SelectItem value="완료">완료</SelectItem>
                  <SelectItem value="취소">취소</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 데스크톱 테이블 */}
          <div className="hidden lg:block overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-24">구분</TableHead>
                  <TableHead className="w-32">일자</TableHead>
                  <TableHead className="w-32">문서번호</TableHead>
                  <TableHead>품목정보</TableHead>
                  <TableHead className="w-24 text-right">수량</TableHead>
                  <TableHead className="w-32 text-right">금액</TableHead>
                  <TableHead className="w-32">창고/위치</TableHead>
                  <TableHead className="w-32">거래처/부서</TableHead>
                  <TableHead className="w-24">상태</TableHead>
                  <TableHead className="w-40">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {getFilteredTransactions().map((transaction) => (
                  <TableRow key={transaction.id}>
                    <TableCell>
                      <Badge className={transaction.type === "입고" ? "bg-blue-600" : "bg-purple-600"}>
                        {transaction.type}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-sm">{transaction.date}</TableCell>
                    <TableCell className="text-sm font-mono">{transaction.documentNo}</TableCell>
                    <TableCell>
                      <div className="flex flex-col">
                        <span className="font-medium">{transaction.itemName}</span>
                        <span className="text-xs text-muted-foreground">{transaction.itemCode} | {transaction.spec}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-right">
                      {transaction.quantity.toLocaleString()} {transaction.unit}
                    </TableCell>
                    <TableCell className="text-right font-medium">
                      {transaction.totalPrice.toLocaleString()}원
                    </TableCell>
                    <TableCell className="text-sm">
                      <div className="flex flex-col">
                        <span>{transaction.warehouse}</span>
                        <span className="text-xs text-muted-foreground">{transaction.location}</span>
                      </div>
                    </TableCell>
                    <TableCell className="text-sm">
                      {transaction.supplier || transaction.customer || transaction.department || "-"}
                    </TableCell>
                    <TableCell>
                      <Badge className={getStatusColor(transaction.status)}>
                        {transaction.status}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div className="flex gap-1">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setSelectedTransaction(transaction);
                            setShowDetailDialog(true);
                          }}
                        >
                          <Eye className="h-3 w-3" />
                        </Button>
                        {transaction.status === "대기" && (
                          <>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => updateStatus(transaction.id, "승인")}
                              className="text-green-600 hover:text-green-700"
                            >
                              승인
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => updateStatus(transaction.id, "취소")}
                              className="text-red-600 hover:text-red-700"
                            >
                              취소
                            </Button>
                          </>
                        )}
                        {transaction.status === "승인" && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => updateStatus(transaction.id, "완료")}
                            className="text-blue-600 hover:text-blue-700"
                          >
                            완료
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 */}
          <div className="lg:hidden space-y-3">
            {getFilteredTransactions().map((transaction) => (
              <Card key={transaction.id} className="border-0 shadow-md hover:shadow-lg transition-shadow">
                <CardContent className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex gap-2">
                      <Badge className={transaction.type === "입고" ? "bg-blue-600" : "bg-purple-600"}>
                        {transaction.type}
                      </Badge>
                      <Badge className={getStatusColor(transaction.status)}>
                        {transaction.status}
                      </Badge>
                    </div>
                    <span className="text-xs text-muted-foreground">{transaction.date}</span>
                  </div>

                  <h4 className="font-bold mb-1">{transaction.itemName}</h4>
                  <p className="text-sm text-muted-foreground mb-2">
                    {transaction.itemCode} | {transaction.spec}
                  </p>

                  <div className="grid grid-cols-2 gap-2 text-sm mb-3">
                    <div>
                      <span className="text-muted-foreground">수량:</span>
                      <span className="ml-1 font-medium">{transaction.quantity.toLocaleString()} {transaction.unit}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">금액:</span>
                      <span className="ml-1 font-medium">{transaction.totalPrice.toLocaleString()}원</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">창고:</span>
                      <span className="ml-1">{transaction.warehouse}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">위치:</span>
                      <span className="ml-1">{transaction.location}</span>
                    </div>
                  </div>

                  <div className="flex gap-2 pt-3 border-t">
                    <Button
                      size="sm"
                      variant="outline"
                      className="flex-1"
                      onClick={() => {
                        setSelectedTransaction(transaction);
                        setShowDetailDialog(true);
                      }}
                    >
                      <Eye className="h-4 w-4 mr-1" />
                      상세
                    </Button>
                    {transaction.status === "대기" && (
                      <>
                        <Button
                          size="sm"
                          className="flex-1 bg-green-600 hover:bg-green-700"
                          onClick={() => updateStatus(transaction.id, "승인")}
                        >
                          승인
                        </Button>
                        <Button
                          size="sm"
                          variant="destructive"
                          className="flex-1"
                          onClick={() => updateStatus(transaction.id, "취소")}
                        >
                          취소
                        </Button>
                      </>
                    )}
                    {transaction.status === "승인" && (
                      <Button
                        size="sm"
                        className="flex-1 bg-blue-600 hover:bg-blue-700"
                        onClick={() => updateStatus(transaction.id, "완료")}
                      >
                        완료
                      </Button>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {getFilteredTransactions().length === 0 && (
            <div className="text-center py-12">
              <Package className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground">등록된 입출고 내역이 없습니다.</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 입출고 등록 다이얼로그 */}
      <Dialog open={showWriteDialog} onOpenChange={setShowWriteDialog}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {transactionType} 등록
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>일자 *</Label>
                <Input
                  type="date"
                  value={formData.date}
                  onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                />
              </div>
              <div>
                <Label>문서번호</Label>
                <Input
                  value={formData.documentNo}
                  onChange={(e) => setFormData({ ...formData, documentNo: e.target.value })}
                  placeholder="자동 생성 또는 수동 입력"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>품목코드 *</Label>
                <Input
                  value={formData.itemCode}
                  onChange={(e) => setFormData({ ...formData, itemCode: e.target.value })}
                  placeholder="예: RM-001"
                />
              </div>
              <div>
                <Label>품목명 *</Label>
                <Input
                  value={formData.itemName}
                  onChange={(e) => setFormData({ ...formData, itemName: e.target.value })}
                  placeholder="예: EGIT-SST"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>규격</Label>
                <Input
                  value={formData.spec}
                  onChange={(e) => setFormData({ ...formData, spec: e.target.value })}
                  placeholder="예: 1219*3500"
                />
              </div>
              <div>
                <Label>단위 *</Label>
                <Select
                  value={formData.unit}
                  onValueChange={(value) => setFormData({ ...formData, unit: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="장">장</SelectItem>
                    <SelectItem value="개">개</SelectItem>
                    <SelectItem value="EA">EA</SelectItem>
                    <SelectItem value="kg">kg</SelectItem>
                    <SelectItem value="m">m</SelectItem>
                    <SelectItem value="box">box</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Label>수량 *</Label>
                <Input
                  type="number"
                  value={formData.quantity}
                  onChange={(e) => {
                    const qty = Number(e.target.value);
                    setFormData({
                      ...formData,
                      quantity: qty,
                      totalPrice: qty * (formData.unitPrice || 0)
                    });
                  }}
                  placeholder="0"
                />
              </div>
              <div>
                <Label>단가</Label>
                <Input
                  type="number"
                  value={formData.unitPrice}
                  onChange={(e) => {
                    const price = Number(e.target.value);
                    setFormData({
                      ...formData,
                      unitPrice: price,
                      totalPrice: (formData.quantity || 0) * price
                    });
                  }}
                  placeholder="0"
                />
              </div>
              <div>
                <Label>총액</Label>
                <Input
                  type="number"
                  value={formData.totalPrice}
                  readOnly
                  className="bg-gray-50"
                />
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>창고 *</Label>
                <Select
                  value={formData.warehouse}
                  onValueChange={(value) => setFormData({ ...formData, warehouse: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1공장 창고">1공장 창고</SelectItem>
                    <SelectItem value="2공장 창고">2공장 창고</SelectItem>
                    <SelectItem value="부자재 창고">부자재 창고</SelectItem>
                    <SelectItem value="완제품 창고">완제품 창고</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>위치</Label>
                <Input
                  value={formData.location}
                  onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                  placeholder="예: A-01"
                />
              </div>
            </div>

            {transactionType === "입고" ? (
              <div>
                <Label>공급업체</Label>
                <Input
                  value={formData.supplier}
                  onChange={(e) => setFormData({ ...formData, supplier: e.target.value })}
                  placeholder="공급업체명"
                />
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>요청부서</Label>
                  <Input
                    value={formData.department}
                    onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                    placeholder="예: 생산1팀"
                  />
                </div>
                <div>
                  <Label>용도</Label>
                  <Input
                    value={formData.purpose}
                    onChange={(e) => setFormData({ ...formData, purpose: e.target.value })}
                    placeholder="예: 생산 투입"
                  />
                </div>
              </div>
            )}

            <div>
              <Label>비고</Label>
              <Textarea
                value={formData.remarks}
                onChange={(e) => setFormData({ ...formData, remarks: e.target.value })}
                placeholder="특이사항 입력"
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowWriteDialog(false)}>
              취소
            </Button>
            <Button onClick={handleSubmit}>
              등록
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 상세보기 다이얼로그 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>입출고 상세 정보</DialogTitle>
            <DialogDescription>
              입출고 거래의 상세 정보를 확인합니다.
            </DialogDescription>
          </DialogHeader>
          {selectedTransaction && (
            <div className="space-y-4 py-4">
              <div className="flex items-center gap-2">
                <Badge className={selectedTransaction.type === "입고" ? "bg-blue-600" : "bg-purple-600"}>
                  {selectedTransaction.type}
                </Badge>
                <Badge className={getStatusColor(selectedTransaction.status)}>
                  {selectedTransaction.status}
                </Badge>
                <span className="text-sm text-muted-foreground ml-auto">{selectedTransaction.id}</span>
              </div>

              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">일자:</span>
                  <span className="ml-2 font-medium">{selectedTransaction.date}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">문서번호:</span>
                  <span className="ml-2 font-medium">{selectedTransaction.documentNo}</span>
                </div>
                <div className="col-span-2">
                  <span className="text-muted-foreground">품목:</span>
                  <span className="ml-2 font-medium">{selectedTransaction.itemName} ({selectedTransaction.itemCode})</span>
                </div>
                <div>
                  <span className="text-muted-foreground">규격:</span>
                  <span className="ml-2">{selectedTransaction.spec}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">수량:</span>
                  <span className="ml-2 font-medium">{selectedTransaction.quantity.toLocaleString()} {selectedTransaction.unit}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">단가:</span>
                  <span className="ml-2">{selectedTransaction.unitPrice.toLocaleString()}원</span>
                </div>
                <div>
                  <span className="text-muted-foreground">총액:</span>
                  <span className="ml-2 font-medium">{selectedTransaction.totalPrice.toLocaleString()}원</span>
                </div>
                <div>
                  <span className="text-muted-foreground">창고:</span>
                  <span className="ml-2">{selectedTransaction.warehouse}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">위치:</span>
                  <span className="ml-2">{selectedTransaction.location}</span>
                </div>
                {selectedTransaction.supplier && (
                  <div className="col-span-2">
                    <span className="text-muted-foreground">공급업체:</span>
                    <span className="ml-2">{selectedTransaction.supplier}</span>
                  </div>
                )}
                {selectedTransaction.department && (
                  <div>
                    <span className="text-muted-foreground">요청부서:</span>
                    <span className="ml-2">{selectedTransaction.department}</span>
                  </div>
                )}
                {selectedTransaction.purpose && (
                  <div>
                    <span className="text-muted-foreground">용도:</span>
                    <span className="ml-2">{selectedTransaction.purpose}</span>
                  </div>
                )}
                <div>
                  <span className="text-muted-foreground">요청자:</span>
                  <span className="ml-2">{selectedTransaction.requestBy}</span>
                </div>
                {selectedTransaction.approvedBy && (
                  <div>
                    <span className="text-muted-foreground">승인자:</span>
                    <span className="ml-2">{selectedTransaction.approvedBy}</span>
                  </div>
                )}
                {selectedTransaction.remarks && (
                  <div className="col-span-2">
                    <span className="text-muted-foreground">비고:</span>
                    <p className="mt-1 p-2 bg-gray-50 rounded">{selectedTransaction.remarks}</p>
                  </div>
                )}
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
              닫기
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
