import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { 
  Plus,
  TrendingUp,
  XCircle,
  Package,
  CheckCircle,
  Clock,
  AlertTriangle
} from "lucide-react";
import { ReceivingWritePage } from "./ReceivingWrite";
import { MaterialRegistration } from "./MaterialRegistration";
import { IncomingInspection } from "./IncomingInspection";

interface MaterialManagementProps {
  defaultTab?: "receiving" | "nonconforming";
}

export function MaterialManagement({ defaultTab = "receiving" }: MaterialManagementProps = {}) {
  const [view, setView] = useState<"list" | "register">("list");
  const [activeTab, setActiveTab] = useState(defaultTab);
  const [receivingView, setReceivingView] = useState<"list" | "write" | "inspection">("list");
  const [receivingData, setReceivingData] = useState<any>(null);

  // 입고 리스트 데이터
  const receivingList = [
    {
      id: "1",
      lotNumber: "250723-04",
      materialNumber: "-",
      item: "EGIT-SST",
      spec: "1219*3500",
      unit: "예",
      quantity: 80,
      weight: "4,160",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionStatus: "검사대상",
      incomingInspection: "합격",
      judgement: "합격",
      managerApproval: "승인완료"
    },
    {
      id: "2",
      lotNumber: "250716-01",
      materialNumber: "-",
      item: "용강코일",
      spec: "EGIT-SST(W)350",
      unit: "롤",
      quantity: 9,
      weight: "9,210",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionStatus: "검사대상",
      incomingInspection: "대기",
      judgement: "대기",
      managerApproval: "대기"
    },
    {
      id: "3",
      lotNumber: "-",
      materialNumber: "-",
      item: "베링용장",
      spec: "3808",
      unit: "EA",
      quantity: 920,
      weight: "-",
      supplier: "대한",
      manufacturer: "대한",
      inspectionStatus: "발령",
      incomingInspection: "검사생략",
      judgement: "검사생략",
      managerApproval: "승인완료"
    }
  ];

  // 부적합품 데이터
  const nonconformingList = [
    {
      id: "NC001",
      lotNumber: "250715-02",
      materialNumber: "M-250715-02",
      item: "EGIT-SST",
      spec: "1219*3500",
      unit: "예",
      quantity: 50,
      weight: "2,600",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionDate: "2024-07-15",
      inspector: "김검사",
      judgement: "불합격",
      managerApproval: "반려",
      nonconformingReason: "두께 기준 미달 (1.35mm, 기준: 1.5ST ±0.15)",
      status: "대기",
      action: "반품요청",
      actionDate: "-"
    },
    {
      id: "NC002",
      lotNumber: "250710-01",
      materialNumber: "M-250710-01",
      item: "용강코일",
      spec: "EGIT-SST(W)350",
      unit: "롤",
      quantity: 5,
      weight: "5,120",
      supplier: "지프하스",
      manufacturer: "KG스틸",
      inspectionDate: "2024-07-10",
      inspector: "박품질",
      judgement: "불합격",
      managerApproval: "반려",
      nonconformingReason: "외관 불량 - 표면 흠집 다수",
      status: "처리완료",
      action: "반품완료",
      actionDate: "2024-07-12"
    },
    {
      id: "NC003",
      lotNumber: "250708-03",
      materialNumber: "M-250708-03",
      item: "알루미늄 가이드레일",
      spec: "6063-T5, 3000mm",
      unit: "M",
      quantity: 150,
      weight: "450",
      supplier: "알텍솔루션",
      manufacturer: "대한알미늄",
      inspectionDate: "2024-07-08",
      inspector: "김검사",
      judgement: "불합격",
      managerApproval: "보류",
      nonconformingReason: "인장강도 기준 미달 (255 N/mm², 기준: ≥270 N/mm²)",
      status: "처리중",
      action: "재검토",
      actionDate: "2024-07-09"
    }
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case "검사대상": return "bg-blue-500 text-white";
      case "검사완료": return "bg-green-500 text-white";
      case "발령": return "bg-purple-500 text-white";
      case "합격": return "bg-green-500 text-white";
      case "불합격": return "bg-red-500 text-white";
      case "검사생략": return "bg-gray-500 text-white";
      case "대기": return "bg-yellow-500 text-white";
      case "승인완료": return "bg-green-500 text-white";
      case "반려": return "bg-red-500 text-white";
      case "보류": return "bg-orange-500 text-white";
      case "처리완료": return "bg-green-500 text-white";
      case "처리중": return "bg-yellow-500 text-white";
      default: return "bg-muted text-white";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "합격":
      case "승인완료":
      case "처리완료":
        return <CheckCircle className="w-3 h-3" />;
      case "대기":
      case "처리중":
        return <Clock className="w-3 h-3" />;
      case "불합격":
      case "반려":
        return <XCircle className="w-3 h-3" />;
      default:
        return <AlertTriangle className="w-3 h-3" />;
    }
  };

  // 자재 등록 뷰
  if (view === "register") {
    return <MaterialRegistration onBack={() => setView("list")} />;
  }

  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>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4 md:space-y-6">
        <TabsList className="grid w-full grid-cols-2 bg-white shadow-sm rounded-xl p-1 border">
          <TabsTrigger 
            value="receiving" 
            className="rounded-lg data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white"
          >
            <TrendingUp className="w-4 h-4 mr-1.5" />
            <span className="hidden sm:inline">입고 관리</span>
            <span className="sm:hidden text-xs">입고</span>
          </TabsTrigger>
          <TabsTrigger 
            value="nonconforming" 
            className="rounded-lg data-[state=active]:bg-gradient-to-r data-[state=active]:from-red-600 data-[state=active]:to-rose-600 data-[state=active]:text-white"
          >
            <XCircle className="w-4 h-4 mr-1.5" />
            <span className="hidden sm:inline">부적합품 관리</span>
            <span className="sm:hidden text-xs">부적합품</span>
          </TabsTrigger>
        </TabsList>

        {/* 입고 관리 탭 */}
        <TabsContent value="receiving" className="mt-0">
          {receivingView === "list" ? (
            <Card className="border-0 shadow-lg bg-white/80 backdrop-blur">
              <CardHeader className="pb-3">
                <CardTitle className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center shadow-md">
                      <Package className="w-5 h-5 text-white" />
                    </div>
                    <div>
                      <h2 className="text-base md:text-lg">입고 리스트</h2>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        총 {receivingList.length}건
                      </p>
                    </div>
                  </div>
                  <Button 
                    onClick={() => setReceivingView("write")} 
                    className="w-full sm:w-auto bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 shadow-md"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    입고 등록
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent className="px-3 md:px-6">
                {/* 데스크톱 테이블 뷰 */}
                <div className="hidden lg:block rounded-xl border overflow-hidden shadow-sm bg-white">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-gradient-to-r from-slate-50 to-blue-50/50 hover:from-slate-50 hover:to-blue-50/50">
                        <TableHead className="font-semibold">로트번호</TableHead>
                        <TableHead className="font-semibold">자재번호</TableHead>
                        <TableHead className="font-semibold">품목</TableHead>
                        <TableHead className="font-semibold">규격</TableHead>
                        <TableHead className="font-semibold">단위</TableHead>
                        <TableHead className="font-semibold">입고량</TableHead>
                        <TableHead className="font-semibold">중량(kg)</TableHead>
                        <TableHead className="font-semibold">납품업체</TableHead>
                        <TableHead className="font-semibold">제조사</TableHead>
                        <TableHead className="font-semibold">검사여부</TableHead>
                        <TableHead className="font-semibold">수입검사</TableHead>
                        <TableHead className="font-semibold">판정</TableHead>
                        <TableHead className="font-semibold">팀장승인</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {receivingList.map((record) => (
                        <TableRow key={record.id} className="hover:bg-blue-50/30">
                          <TableCell className="font-mono text-sm font-medium">{record.lotNumber}</TableCell>
                          <TableCell className="font-mono text-sm">{record.materialNumber}</TableCell>
                          <TableCell className="font-medium">{record.item}</TableCell>
                          <TableCell className="text-sm text-muted-foreground">{record.spec}</TableCell>
                          <TableCell>{record.unit}</TableCell>
                          <TableCell className="font-semibold">{record.quantity}</TableCell>
                          <TableCell className="text-muted-foreground">{record.weight}</TableCell>
                          <TableCell>{record.supplier}</TableCell>
                          <TableCell>{record.manufacturer}</TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(record.inspectionStatus)}>
                              {record.inspectionStatus}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(record.incomingInspection)}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.incomingInspection)}
                                {record.incomingInspection}
                              </span>
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(record.judgement)}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.judgement)}
                                {record.judgement}
                              </span>
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge className={getStatusColor(record.managerApproval)}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.managerApproval)}
                                {record.managerApproval}
                              </span>
                            </Badge>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {/* 모바일 카드 뷰 */}
                <div className="lg:hidden space-y-3">
                  {receivingList.map((record) => (
                    <Card key={record.id} className="border-0 shadow-md hover:shadow-lg transition-shadow bg-white">
                      <CardContent className="p-4">
                        {/* 헤더 영역 */}
                        <div className="flex items-start justify-between gap-2 mb-3 pb-3 border-b">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1.5">
                              <Badge variant="outline" className="font-mono text-[10px] px-1.5 py-0">
                                {record.lotNumber}
                              </Badge>
                              <Badge className={getStatusColor(record.inspectionStatus) + " text-[10px] px-1.5 py-0"}>
                                {record.inspectionStatus}
                              </Badge>
                            </div>
                            <h4 className="font-bold text-base">{record.item}</h4>
                            <p className="text-xs text-muted-foreground mt-0.5">{record.spec}</p>
                          </div>
                        </div>

                        {/* 수량 정보 - 강조 */}
                        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg p-3 mb-3">
                          <div className="grid grid-cols-2 gap-3">
                            <div>
                              <span className="text-[10px] text-muted-foreground block mb-0.5">입고량</span>
                              <p className="font-bold text-lg text-blue-600">{record.quantity} <span className="text-sm">{record.unit}</span></p>
                            </div>
                            <div>
                              <span className="text-[10px] text-muted-foreground block mb-0.5">중량</span>
                              <p className="font-bold text-lg text-indigo-600">{record.weight} <span className="text-sm">kg</span></p>
                            </div>
                          </div>
                        </div>

                        {/* 기본 정보 */}
                        <div className="grid grid-cols-2 gap-2 mb-3 text-xs">
                          <div className="bg-slate-50 rounded-lg p-2">
                            <span className="text-[10px] text-muted-foreground block mb-0.5">납품업체</span>
                            <p className="font-semibold truncate">{record.supplier}</p>
                          </div>
                          <div className="bg-slate-50 rounded-lg p-2">
                            <span className="text-[10px] text-muted-foreground block mb-0.5">제조사</span>
                            <p className="font-semibold truncate">{record.manufacturer}</p>
                          </div>
                        </div>

                        {/* 상태 정보 */}
                        <div className="space-y-2 pt-3 border-t">
                          <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">수입검사</span>
                            <Badge className={getStatusColor(record.incomingInspection) + " text-[10px]"}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.incomingInspection)}
                                {record.incomingInspection}
                              </span>
                            </Badge>
                          </div>
                          <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">판정</span>
                            <Badge className={getStatusColor(record.judgement) + " text-[10px]"}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.judgement)}
                                {record.judgement}
                              </span>
                            </Badge>
                          </div>
                          <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">팀장승인</span>
                            <Badge className={getStatusColor(record.managerApproval) + " text-[10px]"}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.managerApproval)}
                                {record.managerApproval}
                              </span>
                            </Badge>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          ) : receivingView === "write" ? (
            <ReceivingWritePage 
              onBack={() => setReceivingView("list")}
              onInspection={(data) => {
                setReceivingData(data);
                setReceivingView("inspection");
              }}
            />
          ) : receivingView === "inspection" ? (
            <IncomingInspection
              onBack={() => setReceivingView("write")}
              onComplete={() => setReceivingView("list")}
              receivingData={receivingData}
            />
          ) : null}
        </TabsContent>

        {/* 부적합품 관리 탭 */}
        <TabsContent value="nonconforming" className="mt-0">
          <Card className="border-0 shadow-lg bg-white/80 backdrop-blur">
            <CardHeader className="pb-3">
              <CardTitle className="flex flex-col sm:flex-row items-start sm:items-center gap-3">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-red-500 to-rose-500 rounded-xl flex items-center justify-center shadow-md">
                    <XCircle className="w-5 h-5 text-white" />
                  </div>
                  <div>
                    <h2 className="text-base md:text-lg">부적합품 관리</h2>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      수입검사 부적합 이력 • 총 {nonconformingList.length}건
                    </p>
                  </div>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent className="px-3 md:px-6">
              {/* 데스크톱 테이블 뷰 */}
              <div className="hidden lg:block rounded-xl border overflow-hidden shadow-sm bg-white">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gradient-to-r from-red-50 to-rose-50/50 hover:from-red-50 hover:to-rose-50/50">
                      <TableHead className="font-semibold">로트번호</TableHead>
                      <TableHead className="font-semibold">자재번호</TableHead>
                      <TableHead className="font-semibold">품목</TableHead>
                      <TableHead className="font-semibold">규격</TableHead>
                      <TableHead className="font-semibold">수량</TableHead>
                      <TableHead className="font-semibold">납품업체</TableHead>
                      <TableHead className="font-semibold">검사일자</TableHead>
                      <TableHead className="font-semibold">검사자</TableHead>
                      <TableHead className="min-w-[250px] font-semibold">부적합 사유</TableHead>
                      <TableHead className="font-semibold">판정</TableHead>
                      <TableHead className="font-semibold">팀장승인</TableHead>
                      <TableHead className="font-semibold">상태</TableHead>
                      <TableHead className="font-semibold">조치</TableHead>
                      <TableHead className="font-semibold">조치일</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {nonconformingList.map((record) => (
                      <TableRow key={record.id} className="hover:bg-red-50/30">
                        <TableCell className="font-mono text-sm font-medium">{record.lotNumber}</TableCell>
                        <TableCell className="font-mono text-sm">{record.materialNumber}</TableCell>
                        <TableCell className="font-medium">{record.item}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">{record.spec}</TableCell>
                        <TableCell className="font-semibold">{record.quantity} {record.unit}</TableCell>
                        <TableCell>{record.supplier}</TableCell>
                        <TableCell>{record.inspectionDate}</TableCell>
                        <TableCell>{record.inspector}</TableCell>
                        <TableCell>
                          <div className="text-sm text-red-600 font-medium">{record.nonconformingReason}</div>
                        </TableCell>
                        <TableCell>
                          <Badge className={getStatusColor(record.judgement)}>
                            <span className="flex items-center gap-1">
                              {getStatusIcon(record.judgement)}
                              {record.judgement}
                            </span>
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={getStatusColor(record.managerApproval)}>
                            <span className="flex items-center gap-1">
                              {getStatusIcon(record.managerApproval)}
                              {record.managerApproval}
                            </span>
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={getStatusColor(record.status)}>
                            <span className="flex items-center gap-1">
                              {getStatusIcon(record.status)}
                              {record.status}
                            </span>
                          </Badge>
                        </TableCell>
                        <TableCell className="font-medium">{record.action}</TableCell>
                        <TableCell>{record.actionDate}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 뷰 */}
              <div className="lg:hidden space-y-3">
                {nonconformingList.map((record) => (
                  <Card key={record.id} className="border-0 shadow-md hover:shadow-lg transition-shadow bg-gradient-to-br from-white to-red-50/30">
                    <CardContent className="p-4">
                      {/* 헤더 영역 */}
                      <div className="flex items-start justify-between gap-2 mb-3 pb-3 border-b border-red-100">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1.5 flex-wrap">
                            <Badge variant="outline" className="font-mono text-[10px] px-1.5 py-0 border-red-300">
                              {record.lotNumber}
                            </Badge>
                            <Badge className={getStatusColor(record.status) + " text-[10px] px-1.5 py-0"}>
                              <span className="flex items-center gap-1">
                                {getStatusIcon(record.status)}
                                {record.status}
                              </span>
                            </Badge>
                          </div>
                          <h4 className="font-bold text-base">{record.item}</h4>
                          <p className="text-xs text-muted-foreground mt-0.5">{record.spec}</p>
                        </div>
                      </div>

                      {/* 수량 정보 */}
                      <div className="bg-gradient-to-r from-red-50 to-rose-50 border border-red-200 rounded-lg p-3 mb-3">
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <span className="text-[10px] text-muted-foreground block mb-0.5">수량</span>
                            <p className="font-bold text-lg text-red-600">{record.quantity} <span className="text-sm">{record.unit}</span></p>
                          </div>
                          <div>
                            <span className="text-[10px] text-muted-foreground block mb-0.5">중량</span>
                            <p className="font-bold text-lg text-rose-600">{record.weight} <span className="text-sm">kg</span></p>
                          </div>
                        </div>
                      </div>

                      {/* 기본 정보 */}
                      <div className="grid grid-cols-2 gap-2 mb-3 text-xs">
                        <div className="bg-white rounded-lg p-2 border border-red-100">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">납품업체</span>
                          <p className="font-semibold truncate">{record.supplier}</p>
                        </div>
                        <div className="bg-white rounded-lg p-2 border border-red-100">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">제조사</span>
                          <p className="font-semibold truncate">{record.manufacturer}</p>
                        </div>
                        <div className="bg-white rounded-lg p-2 border border-red-100">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">검사일자</span>
                          <p className="font-semibold">{record.inspectionDate}</p>
                        </div>
                        <div className="bg-white rounded-lg p-2 border border-red-100">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">검사자</span>
                          <p className="font-semibold">{record.inspector}</p>
                        </div>
                      </div>

                      {/* 부적합 사유 - 강조 */}
                      <div className="bg-red-100 border-2 border-red-300 rounded-lg p-3 mb-3">
                        <div className="flex items-start gap-2">
                          <AlertTriangle className="w-4 h-4 text-red-600 shrink-0 mt-0.5" />
                          <div className="flex-1">
                            <p className="text-[10px] text-red-600 font-semibold mb-1">부적합 사유</p>
                            <p className="text-xs text-red-700 font-medium leading-relaxed">{record.nonconformingReason}</p>
                          </div>
                        </div>
                      </div>

                      {/* 상태 정보 */}
                      <div className="space-y-2 mb-3">
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-muted-foreground">판정</span>
                          <Badge className={getStatusColor(record.judgement) + " text-[10px]"}>
                            <span className="flex items-center gap-1">
                              {getStatusIcon(record.judgement)}
                              {record.judgement}
                            </span>
                          </Badge>
                        </div>
                        <div className="flex items-center justify-between text-xs">
                          <span className="text-muted-foreground">팀장승인</span>
                          <Badge className={getStatusColor(record.managerApproval) + " text-[10px]"}>
                            <span className="flex items-center gap-1">
                              {getStatusIcon(record.managerApproval)}
                              {record.managerApproval}
                            </span>
                          </Badge>
                        </div>
                      </div>

                      {/* 조치 정보 */}
                      <div className="grid grid-cols-2 gap-2 text-xs pt-3 border-t border-red-100">
                        <div className="bg-slate-50 rounded-lg p-2">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">조치</span>
                          <p className="font-semibold">{record.action}</p>
                        </div>
                        <div className="bg-slate-50 rounded-lg p-2">
                          <span className="text-[10px] text-muted-foreground block mb-0.5">조치일</span>
                          <p className="font-semibold">{record.actionDate}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
