import React, { 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from './ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import { 
  GitBranch, 
  Search, 
  Plus, 
  Edit, 
  Trash2,
  Eye,
  Copy,
  FileText,
  Package,
  Layers,
  CheckCircle,
  XCircle,
  Clock
} from 'lucide-react';

interface BOMItem {
  id: string;
  componentCode: string;
  componentName: string;
  quantity: number;
  unit: string;
  note: string;
}

interface BOM {
  id: string;
  bomCode: string;
  bomName: string;
  bomType: '부품' | '완제품';
  modelCode: string;
  modelName: string;
  version: string;
  status: '작성중' | '승인' | '폐기';
  items: BOMItem[];
  createdDate: string;
  createdBy: string;
  approvedDate?: string;
  approvedBy?: string;
}

export function ProductionBOMManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('전체');
  const [selectedStatus, setSelectedStatus] = useState('전체');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingBOM, setEditingBOM] = useState<BOM | null>(null);
  const [bomItems, setBomItems] = useState<BOMItem[]>([]);

  // 모의 데이터
  const boms: BOM[] = [
    {
      id: 'BOM001',
      bomCode: 'BOM-SCREEN-001',
      bomName: '스크린 기본형 BOM',
      bomType: '완제품',
      modelCode: 'SCR-100',
      modelName: '스크린 기본형',
      version: 'v1.2',
      status: '승인',
      items: [
        { id: '1', componentCode: 'MAT-001', componentName: '알루미늄 프로파일', quantity: 2, unit: 'EA', note: '상하단' },
        { id: '2', componentCode: 'MAT-002', componentName: '패브릭 원단', quantity: 1.5, unit: 'M', note: '차광' },
        { id: '3', componentCode: 'MAT-003', componentName: '볼트 M6', quantity: 8, unit: 'EA', note: '' },
        { id: '4', componentCode: 'MAT-004', componentName: '모터', quantity: 1, unit: 'EA', note: '자동형' },
      ],
      createdDate: '2025-01-15',
      createdBy: '김철수',
      approvedDate: '2025-01-20',
      approvedBy: '이영희'
    },
    {
      id: 'BOM002',
      bomCode: 'BOM-SLAT-001',
      bomName: '슬랫 표준형 BOM',
      bomType: '완제품',
      modelCode: 'SLT-200',
      modelName: '슬랫 표준형',
      version: 'v2.0',
      status: '승인',
      items: [
        { id: '1', componentCode: 'MAT-005', componentName: '알루미늄 슬랫', quantity: 20, unit: 'EA', note: '50mm' },
        { id: '2', componentCode: 'MAT-006', componentName: '헤드박스', quantity: 1, unit: 'EA', note: '' },
        { id: '3', componentCode: 'MAT-007', componentName: '하단바', quantity: 1, unit: 'EA', note: '' },
        { id: '4', componentCode: 'MAT-008', componentName: '연결줄', quantity: 2, unit: 'M', note: '' },
      ],
      createdDate: '2025-02-01',
      createdBy: '박민수',
      approvedDate: '2025-02-05',
      approvedBy: '이영희'
    },
    {
      id: 'BOM003',
      bomCode: 'BOM-PART-001',
      bomName: '헤드박스 부품 BOM',
      bomType: '부품',
      modelCode: 'MAT-006',
      modelName: '헤드박스',
      version: 'v1.0',
      status: '승인',
      items: [
        { id: '1', componentCode: 'RAW-001', componentName: '철판 1.2T', quantity: 0.5, unit: 'M', note: '' },
        { id: '2', componentCode: 'RAW-002', componentName: '베어링', quantity: 2, unit: 'EA', note: '' },
        { id: '3', componentCode: 'RAW-003', componentName: '스프링', quantity: 1, unit: 'EA', note: '' },
      ],
      createdDate: '2025-01-10',
      createdBy: '정수진',
      approvedDate: '2025-01-12',
      approvedBy: '최동훈'
    },
    {
      id: 'BOM004',
      bomCode: 'BOM-BEND-001',
      bomName: '절곡 제품 BOM',
      bomType: '완제품',
      modelCode: 'BND-300',
      modelName: '절곡 제품',
      version: 'v1.1',
      status: '승인',
      items: [
        { id: '1', componentCode: 'MAT-009', componentName: '절곡 프레임', quantity: 1, unit: 'EA', note: '' },
        { id: '2', componentCode: 'MAT-010', componentName: '고정 브라켓', quantity: 4, unit: 'EA', note: '' },
        { id: '3', componentCode: 'MAT-011', componentName: '나사 M8', quantity: 16, unit: 'EA', note: '' },
      ],
      createdDate: '2025-02-10',
      createdBy: '강민호',
      approvedDate: '2025-02-15',
      approvedBy: '이영희'
    },
    {
      id: 'BOM005',
      bomCode: 'BOM-NEW-001',
      bomName: '신규 개발 제품 BOM',
      bomType: '완제품',
      modelCode: 'NEW-400',
      modelName: '신규 개발 제품',
      version: 'v0.1',
      status: '작성중',
      items: [
        { id: '1', componentCode: 'MAT-012', componentName: '메인 프레임', quantity: 1, unit: 'EA', note: '설계 진행중' },
      ],
      createdDate: '2025-03-01',
      createdBy: '송지은',
    },
  ];

  const bomTypes = ['전체', '부품', '완제품'];
  const statuses = ['전체', '작성중', '승인', '폐기'];

  const filteredBOMs = boms.filter(bom => {
    const matchesSearch = bom.bomCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         bom.bomName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         bom.modelCode.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = selectedType === '전체' || bom.bomType === selectedType;
    const matchesStatus = selectedStatus === '전체' || bom.status === selectedStatus;
    return matchesSearch && matchesType && matchesStatus;
  });

  const getStatusIcon = (status: string) => {
    switch (status) {
      case '승인': return <CheckCircle className="h-4 w-4 text-green-500" />;
      case '작성중': return <Clock className="h-4 w-4 text-orange-500" />;
      case '폐기': return <XCircle className="h-4 w-4 text-red-500" />;
      default: return null;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '승인': return 'default';
      case '작성중': return 'secondary';
      case '폐기': return 'destructive';
      default: return 'default';
    }
  };

  const handleEdit = (bom: BOM) => {
    setEditingBOM(bom);
    setBomItems(bom.items);
    setIsDialogOpen(true);
  };

  const handleAddNew = () => {
    setEditingBOM(null);
    setBomItems([]);
    setIsDialogOpen(true);
  };

  const addBOMItem = () => {
    const newItem: BOMItem = {
      id: Date.now().toString(),
      componentCode: '',
      componentName: '',
      quantity: 1,
      unit: 'EA',
      note: ''
    };
    setBomItems([...bomItems, newItem]);
  };

  const removeBOMItem = (id: string) => {
    setBomItems(bomItems.filter(item => item.id !== id));
  };

  const updateBOMItem = (id: string, field: keyof BOMItem, value: any) => {
    setBomItems(bomItems.map(item => 
      item.id === id ? { ...item, [field]: value } : item
    ));
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="mb-2">BOM 관리</h1>
          <p className="text-muted-foreground">
            부품 및 완제품의 BOM(Bill of Materials)을 관리합니다.
          </p>
        </div>
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={handleAddNew}>
              <Plus className="h-4 w-4 mr-2" />
              BOM 생성
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editingBOM ? 'BOM 수정' : '신규 BOM 생성'}</DialogTitle>
              <DialogDescription>
                {editingBOM ? '기존 BOM을 수정합니다.' : '새로운 BOM을 생성합니다.'}
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-6">
              {/* 기본 정보 */}
              <div className="space-y-4">
                <h3 className="font-medium">기본 정보</h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="bomCode">BOM 코드</Label>
                    <Input
                      id="bomCode"
                      placeholder="BOM-XXX-001"
                      defaultValue={editingBOM?.bomCode}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="bomName">BOM 명칭</Label>
                    <Input
                      id="bomName"
                      placeholder="제품 BOM 명칭"
                      defaultValue={editingBOM?.bomName}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="bomType">BOM 타입</Label>
                    <Select defaultValue={editingBOM?.bomType || '완제품'}>
                      <SelectTrigger id="bomType">
                        <SelectValue placeholder="타입 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="부품">부품</SelectItem>
                        <SelectItem value="완제품">완제품</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="modelCode">모델/품목 코드</Label>
                    <Input
                      id="modelCode"
                      placeholder="SCR-100"
                      defaultValue={editingBOM?.modelCode}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="modelName">모델/품목명</Label>
                    <Input
                      id="modelName"
                      placeholder="스크린 기본형"
                      defaultValue={editingBOM?.modelName}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="version">버전</Label>
                    <Input
                      id="version"
                      placeholder="v1.0"
                      defaultValue={editingBOM?.version || 'v1.0'}
                    />
                  </div>
                </div>
              </div>

              {/* 구성품 목록 */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="font-medium">구성품 목록</h3>
                  <Button type="button" variant="outline" size="sm" onClick={addBOMItem}>
                    <Plus className="h-4 w-4 mr-2" />
                    구성품 추가
                  </Button>
                </div>

                {bomItems.length === 0 ? (
                  <div className="text-center py-8 border-2 border-dashed rounded-lg">
                    <Package className="h-12 w-12 text-muted-foreground mx-auto mb-2" />
                    <p className="text-muted-foreground">구성품을 추가하세요</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {bomItems.map((item, index) => (
                      <Card key={item.id}>
                        <CardContent className="p-4">
                          <div className="flex items-start gap-4">
                            <div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary/10 shrink-0">
                              <span className="text-sm">{index + 1}</span>
                            </div>
                            <div className="flex-1 grid grid-cols-1 md:grid-cols-5 gap-3">
                              <div className="space-y-1">
                                <Label className="text-xs">부품 코드</Label>
                                <Input
                                  placeholder="MAT-001"
                                  value={item.componentCode}
                                  onChange={(e) => updateBOMItem(item.id, 'componentCode', e.target.value)}
                                />
                              </div>
                              <div className="space-y-1">
                                <Label className="text-xs">부품명</Label>
                                <Input
                                  placeholder="부품명"
                                  value={item.componentName}
                                  onChange={(e) => updateBOMItem(item.id, 'componentName', e.target.value)}
                                />
                              </div>
                              <div className="space-y-1">
                                <Label className="text-xs">수량</Label>
                                <Input
                                  type="number"
                                  placeholder="1"
                                  value={item.quantity}
                                  onChange={(e) => updateBOMItem(item.id, 'quantity', parseFloat(e.target.value))}
                                />
                              </div>
                              <div className="space-y-1">
                                <Label className="text-xs">단위</Label>
                                <Select
                                  value={item.unit}
                                  onValueChange={(value) => updateBOMItem(item.id, 'unit', value)}
                                >
                                  <SelectTrigger>
                                    <SelectValue />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="EA">EA</SelectItem>
                                    <SelectItem value="M">M</SelectItem>
                                    <SelectItem value="KG">KG</SelectItem>
                                    <SelectItem value="SET">SET</SelectItem>
                                    <SelectItem value="BOX">BOX</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                              <div className="space-y-1">
                                <Label className="text-xs">비고</Label>
                                <Input
                                  placeholder="비고"
                                  value={item.note}
                                  onChange={(e) => updateBOMItem(item.id, 'note', e.target.value)}
                                />
                              </div>
                            </div>
                            <Button
                              type="button"
                              variant="ghost"
                              size="sm"
                              onClick={() => removeBOMItem(item.id)}
                              className="shrink-0"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                )}
              </div>

              <div className="flex justify-end gap-2 pt-4 border-t">
                <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                  취소
                </Button>
                <Button onClick={() => setIsDialogOpen(false)}>
                  {editingBOM ? '수정' : '생성'}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>전체 BOM</CardTitle>
            <GitBranch className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{boms.length}</div>
            <p className="text-xs text-muted-foreground">등록된 BOM 수</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>완제품 BOM</CardTitle>
            <Package className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-500">
              {boms.filter(b => b.bomType === '완제품').length}
            </div>
            <p className="text-xs text-muted-foreground">완제품</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>부품 BOM</CardTitle>
            <Layers className="h-4 w-4 text-purple-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-500">
              {boms.filter(b => b.bomType === '부품').length}
            </div>
            <p className="text-xs text-muted-foreground">부품</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>승인 대기</CardTitle>
            <Clock className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-500">
              {boms.filter(b => b.status === '작성중').length}
            </div>
            <p className="text-xs text-muted-foreground">작성중</p>
          </CardContent>
        </Card>
      </div>

      {/* 검색 및 필터 */}
      <Card>
        <CardHeader>
          <CardTitle>BOM 목록</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="BOM 코드, BOM명, 모델코드로 검색..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <div className="flex gap-2">
              <Select value={selectedType} onValueChange={setSelectedType}>
                <SelectTrigger className="w-[120px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {bomTypes.map((type) => (
                    <SelectItem key={type} value={type}>
                      {type}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                <SelectTrigger className="w-[120px]">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statuses.map((status) => (
                    <SelectItem key={status} value={status}>
                      {status}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 데스크톱 테이블 뷰 */}
          <div className="hidden md:block">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left p-3">BOM 코드</th>
                  <th className="text-left p-3">BOM 명칭</th>
                  <th className="text-left p-3">타입</th>
                  <th className="text-left p-3">모델/품목</th>
                  <th className="text-left p-3">버전</th>
                  <th className="text-left p-3">구성품 수</th>
                  <th className="text-left p-3">상태</th>
                  <th className="text-left p-3">작업</th>
                </tr>
              </thead>
              <tbody>
                {filteredBOMs.map((bom) => (
                  <tr key={bom.id} className="border-b hover:bg-accent">
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <GitBranch className="h-4 w-4 text-muted-foreground" />
                        <span className="font-mono">{bom.bomCode}</span>
                      </div>
                    </td>
                    <td className="p-3">
                      <div>
                        <p className="font-medium">{bom.bomName}</p>
                        <p className="text-sm text-muted-foreground">
                          작성: {bom.createdBy} · {bom.createdDate}
                        </p>
                      </div>
                    </td>
                    <td className="p-3">
                      <Badge variant={bom.bomType === '완제품' ? 'default' : 'outline'}>
                        {bom.bomType}
                      </Badge>
                    </td>
                    <td className="p-3">
                      <div>
                        <p className="font-medium">{bom.modelCode}</p>
                        <p className="text-sm text-muted-foreground">{bom.modelName}</p>
                      </div>
                    </td>
                    <td className="p-3">
                      <Badge variant="outline">{bom.version}</Badge>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <Layers className="h-4 w-4 text-muted-foreground" />
                        {bom.items.length}개
                      </div>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(bom.status)}
                        <Badge variant={getStatusColor(bom.status)}>
                          {bom.status}
                        </Badge>
                      </div>
                    </td>
                    <td className="p-3">
                      <div className="flex gap-2">
                        <Button variant="ghost" size="sm">
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => handleEdit(bom)}>
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <Copy className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="sm">
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 모바일 카드 뷰 */}
          <div className="md:hidden space-y-4">
            {filteredBOMs.map((bom) => (
              <Card key={bom.id}>
                <CardContent className="p-4 space-y-3">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant={bom.bomType === '완제품' ? 'default' : 'outline'}>
                          {bom.bomType}
                        </Badge>
                        <Badge variant="outline">{bom.version}</Badge>
                        <div className="flex items-center gap-1">
                          {getStatusIcon(bom.status)}
                          <Badge variant={getStatusColor(bom.status)}>
                            {bom.status}
                          </Badge>
                        </div>
                      </div>
                      <p className="font-medium">{bom.bomName}</p>
                      <p className="text-sm text-muted-foreground font-mono">{bom.bomCode}</p>
                    </div>
                  </div>

                  <div className="space-y-2 text-sm">
                    <div className="flex items-center gap-2 text-muted-foreground">
                      <Package className="h-3 w-3" />
                      모델: {bom.modelCode} - {bom.modelName}
                    </div>
                    <div className="flex items-center gap-2 text-muted-foreground">
                      <Layers className="h-3 w-3" />
                      구성품: {bom.items.length}개
                    </div>
                    <div className="flex items-center gap-2 text-muted-foreground">
                      <FileText className="h-3 w-3" />
                      작성: {bom.createdBy} · {bom.createdDate}
                    </div>
                    {bom.approvedDate && (
                      <div className="flex items-center gap-2 text-muted-foreground">
                        <CheckCircle className="h-3 w-3" />
                        승인: {bom.approvedBy} · {bom.approvedDate}
                      </div>
                    )}
                  </div>

                  {/* 구성품 미리보기 */}
                  <div className="border-t pt-3">
                    <p className="text-sm font-medium mb-2">구성품 목록</p>
                    <div className="space-y-1">
                      {bom.items.slice(0, 3).map((item) => (
                        <div key={item.id} className="text-sm text-muted-foreground flex justify-between">
                          <span>• {item.componentName}</span>
                          <span>{item.quantity} {item.unit}</span>
                        </div>
                      ))}
                      {bom.items.length > 3 && (
                        <p className="text-sm text-muted-foreground">
                          외 {bom.items.length - 3}개 구성품
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" className="flex-1">
                      <Eye className="h-4 w-4 mr-1" />
                      보기
                    </Button>
                    <Button variant="outline" size="sm" className="flex-1" onClick={() => handleEdit(bom)}>
                      <Edit className="h-4 w-4 mr-1" />
                      수정
                    </Button>
                    <Button variant="outline" size="sm">
                      <Copy className="h-4 w-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {filteredBOMs.length === 0 && (
            <div className="text-center py-12">
              <GitBranch className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <p className="text-muted-foreground">검색 결과가 없습니다.</p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}