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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Textarea } from "./ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "./ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "./ui/alert-dialog";
import { toast } from "sonner@2.0.3";
import { Search, Plus, Calculator, Edit, Trash2, Eye, FileText, History, CheckCircle } from "lucide-react";
import { useData } from "./contexts/DataContext";
import type { ProductBOMTemplate, BOMCalculationRule } from "./contexts/DataContext";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { BOMTemplateRegistration } from "./BOMTemplateRegistration";

export function BOMTemplateManagement() {
  const { bomTemplates = [], reviseBOMTemplate, finalizeBOMTemplate, deleteBOMTemplate } = useData();
  
  const [showRegistrationPage, setShowRegistrationPage] = useState(false);
  
  const [searchTerm, setSearchTerm] = useState("");
  const [filterProductType, setFilterProductType] = useState("all");
  const [filterStatus, setFilterStatus] = useState("all");
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<ProductBOMTemplate | null>(null);
  const [selectedRevision, setSelectedRevision] = useState<number | null>(null);
  
  // Form state (수정용)
  const [formData, setFormData] = useState({
    templateCode: "",
    templateName: "",
    productType: "SCREEN" as "SCREEN" | "STEEL",
    productModel: "",
    status: "active" as const
  });
  
  const [bomRules, setBomRules] = useState<BOMCalculationRule[]>([]);
  const [revisionReason, setRevisionReason] = useState("");

  // 통계 계산
  const stats = [
    {
      title: "전체 템플릿",
      value: bomTemplates?.length || 0,
      description: "등록된 템플릿",
      icon: Calculator,
      color: "blue"
    },
    {
      title: "활성 템플릿",
      value: bomTemplates?.filter(t => t.status === 'active').length || 0,
      description: "사용 가능",
      icon: CheckCircle,
      color: "green"
    },
    {
      title: "확정된 템플릿",
      value: bomTemplates?.filter(t => t.isFinal).length || 0,
      description: "최종 확정",
      icon: FileText,
      color: "purple"
    },
    {
      title: "수정 이력",
      value: bomTemplates?.reduce((sum, t) => sum + (t.revisions?.length || 0), 0) || 0,
      description: "전체 수정 건수",
      icon: History,
      color: "orange"
    }
  ];

  // 필터링된 템플릿 목록
  const filteredTemplates = (bomTemplates || []).filter(template => {
    const matchesSearch = 
      template.templateName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (template.templateCode || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (template.productModel && template.productModel.toLowerCase().includes(searchTerm.toLowerCase()));
    const matchesType = filterProductType === "all" || template.productType === filterProductType;
    const matchesStatus = filterStatus === "all" || template.status === filterStatus;
    return matchesSearch && matchesType && matchesStatus;
  });

  // 템플릿 코드 자동 생성
  const generateTemplateCode = () => {
    const maxNumber = (bomTemplates || [])
      .map(t => {
        const match = (t.templateCode || '').match(/\d+$/);
        return match ? parseInt(match[0]) : 0;
      })
      .reduce((max, num) => Math.max(max, num), 0);
    return `BOM-TEMPLATE-${String(maxNumber + 1).padStart(3, '0')}`;
  };

  // BOM 규칙 추가
  const handleAddBOMRule = () => {
    setBomRules([...bomRules, {
      partName: "",
      partCode: "",
      quantityFormula: "",
      unit: "EA",
      description: "",
      roundingRule: "ceil"
    }]);
  };

  // BOM 규칙 삭제
  const handleRemoveBOMRule = (index: number) => {
    setBomRules(bomRules.filter((_, i) => i !== index));
  };

  // BOM 규칙 업데이트
  const handleUpdateBOMRule = (index: number, field: keyof BOMCalculationRule, value: any) => {
    const updated = [...bomRules];
    updated[index] = { ...updated[index], [field]: value };
    setBomRules(updated);
  };

  // 생성 폼 열기
  const handleOpenCreate = () => {
    setShowRegistrationPage(true);
  };

  // 수정 폼 열기
  const handleOpenEdit = (template: ProductBOMTemplate) => {
    if (template.isFinal) {
      toast.error("확정된 템플릿은 수정할 수 없습니다.");
      return;
    }
    
    setSelectedTemplate(template);
    setFormData({
      templateCode: template.templateCode,
      templateName: template.templateName,
      productType: template.productType,
      productModel: template.productModel || "",
      status: template.status
    });
    setBomRules(template.bomRules.map(rule => ({ ...rule })));
    setRevisionReason("");
    setIsEditDialogOpen(true);
  };

  // 템플릿 수정
  const handleUpdate = () => {
    if (!selectedTemplate) return;
    
    if (!formData.templateName || bomRules.length === 0) {
      toast.error("템플릿명과 최소 1개 이상의 BOM 규칙을 입력해주세요.");
      return;
    }

    if (!revisionReason) {
      toast.error("수정 사유를 입력해주세요.");
      return;
    }

    const updates = {
      templateName: formData.templateName,
      productType: formData.productType,
      productModel: formData.productModel,
      bomRules: bomRules,
      status: formData.status,
      updatedAt: new Date().toISOString().split('T')[0],
      updatedBy: '시스템'
    };

    reviseBOMTemplate(selectedTemplate.id, updates, revisionReason, '시스템');
    setIsEditDialogOpen(false);
    setSelectedTemplate(null);
    toast.success(`BOM 템플릿 "${formData.templateName}"이 수정되었습니다. (${selectedTemplate.currentRevision + 1}차 수정)`);
  };

  // 조회 폼 열기
  const handleOpenView = (template: ProductBOMTemplate) => {
    setSelectedTemplate(template);
    setSelectedRevision(null);
    setIsViewDialogOpen(true);
  };

  // 최종 확정
  const handleFinalize = (template: ProductBOMTemplate) => {
    if (template.isFinal) {
      toast.error("이미 확정된 템플릿입니다.");
      return;
    }
    
    finalizeBOMTemplate(template.id, '시스템');
    toast.success(`BOM 템플릿 "${template.templateName}"이 최종 확정되었습니다.`);
  };

  // 삭제
  const handleDelete = (template: ProductBOMTemplate) => {
    if (template.isFinal) {
      toast.error("확정된 템플릿은 삭제할 수 없습니다.");
      return;
    }
    
    deleteBOMTemplate(template.id);
    toast.success(`BOM 템플릿 "${template.templateName}"이 삭제되었습니다.`);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge className="bg-green-500">활성</Badge>;
      case 'inactive':
        return <Badge className="bg-gray-500">비활성</Badge>;
      case 'finalized':
        return <Badge className="bg-purple-500">확정</Badge>;
      case 'draft':
        return <Badge className="bg-yellow-500">초안</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  const getProductTypeBadge = (type: string) => {
    return type === 'SCREEN' 
      ? <Badge className="bg-blue-500">스크린</Badge>
      : <Badge className="bg-green-600">철재</Badge>;
  };

  // 수식 검증 함수
  const validateFormula = (formula: string) => {
    try {
      // W, H를 임시값으로 대체하여 계산 가능한지 확인
      const testFormula = formula
        .replace(/W/g, '1000')
        .replace(/H/g, '2000');
      eval(testFormula);
      return true;
    } catch {
      return false;
    }
  };

  // 등록 페이지 표시 시
  if (showRegistrationPage) {
    return <BOMTemplateRegistration onBack={() => setShowRegistrationPage(false)} />;
  }

  return (
    <PageLayout>
      <PageHeader
        title="제품 BOM 계산 템플릿 관리"
        description="오픈사이즈 기반 부품별 수량 자동 계산 수식 관리"
        icon={Calculator}
        actions={
          <Button onClick={handleOpenCreate}>
            <Plus className="h-5 w-5 mr-2" />
            템플릿 등록
          </Button>
        }
      />

      <StatCards stats={stats} />

      {/* 검색 및 필터 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <Input
                placeholder="템플릿명, 코드, 제품 모델로 검색..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select value={filterProductType} onValueChange={setFilterProductType}>
              <SelectTrigger className="w-full md:w-40">
                <SelectValue placeholder="제품 타입" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체 타입</SelectItem>
                <SelectItem value="SCREEN">스크린</SelectItem>
                <SelectItem value="STEEL">철재</SelectItem>
              </SelectContent>
            </Select>
            <Select value={filterStatus} onValueChange={setFilterStatus}>
              <SelectTrigger className="w-full md:w-32">
                <SelectValue placeholder="상태" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체 상태</SelectItem>
                <SelectItem value="active">활성</SelectItem>
                <SelectItem value="inactive">비활성</SelectItem>
                <SelectItem value="finalized">확정</SelectItem>
                <SelectItem value="draft">초안</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 템플릿 목록 테이블 */}
      <Card>
        <CardHeader>
          <CardTitle>BOM 템플릿 목록 ({filteredTemplates.length}건)</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>코드</TableHead>
                  <TableHead>템플릿명</TableHead>
                  <TableHead>제품 타입</TableHead>
                  <TableHead>제품 모델</TableHead>
                  <TableHead>BOM 규칙 수</TableHead>
                  <TableHead>상태</TableHead>
                  <TableHead>수정 차수</TableHead>
                  <TableHead className="text-right">관리</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredTemplates.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center text-gray-500 py-8">
                      등록된 BOM 템플릿이 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredTemplates.map((template) => (
                    <TableRow key={template.id}>
                      <TableCell className="font-mono">{template.templateCode}</TableCell>
                      <TableCell className="font-medium">{template.templateName}</TableCell>
                      <TableCell>{getProductTypeBadge(template.productType)}</TableCell>
                      <TableCell>{template.productModel || '-'}</TableCell>
                      <TableCell>{template.bomRules.length}개</TableCell>
                      <TableCell>{getStatusBadge(template.status)}</TableCell>
                      <TableCell>
                        {template.currentRevision > 0 ? (
                          <Badge variant="outline">{template.currentRevision}차 수정</Badge>
                        ) : (
                          <span className="text-gray-400">최초</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleOpenView(template)}
                          >
                            <Eye className="h-3 w-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleOpenEdit(template)}
                            disabled={template.isFinal}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                          {!template.isFinal && (
                            <Button
                              size="sm"
                              variant="outline"
                              className="text-purple-600 hover:text-purple-700"
                              onClick={() => handleFinalize(template)}
                            >
                              <CheckCircle className="h-3 w-3" />
                            </Button>
                          )}
                          <AlertDialog>
                            <AlertDialogTrigger asChild>
                              <Button
                                size="sm"
                                variant="outline"
                                className="text-red-600 hover:text-red-700"
                                disabled={template.isFinal}
                              >
                                <Trash2 className="h-3 w-3" />
                              </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                              <AlertDialogHeader>
                                <AlertDialogTitle>템플릿 삭제</AlertDialogTitle>
                                <AlertDialogDescription>
                                  "{template.templateName}" 템플릿을 삭제하시겠습니까?<br />
                                  이 작업은 되돌릴 수 없습니다.
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter>
                                <AlertDialogCancel>취소</AlertDialogCancel>
                                <AlertDialogAction
                                  onClick={() => handleDelete(template)}
                                  className="bg-red-600 hover:bg-red-700"
                                >
                                  삭제
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 템플릿 수정 다이얼로그 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>BOM 템플릿 수정</DialogTitle>
            <DialogDescription>
              템플릿을 수정합니다. 수정 시 이력이 자동으로 저장됩니다.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4 px-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>템플릿 코드</Label>
                <Input value={formData.templateCode} disabled />
              </div>
              <div className="space-y-2">
                <Label>제품 타입 *</Label>
                <Select
                  value={formData.productType}
                  onValueChange={(value: "SCREEN" | "STEEL") => setFormData({ ...formData, productType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="SCREEN">스크린</SelectItem>
                    <SelectItem value="STEEL">철재</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>템플릿명 *</Label>
                <Input
                  value={formData.templateName}
                  onChange={(e) => setFormData({ ...formData, templateName: e.target.value })}
                />
              </div>
              <div className="space-y-2">
                <Label>제품 모델</Label>
                <Input
                  value={formData.productModel}
                  onChange={(e) => setFormData({ ...formData, productModel: e.target.value })}
                />
              </div>
            </div>

            <div className="border-t pt-4">
              <div className="flex items-center justify-between mb-4">
                <Label>BOM 계산 규칙 *</Label>
                <Button type="button" onClick={handleAddBOMRule} size="sm">
                  <Plus className="h-4 w-4 mr-2" />
                  규칙 추가
                </Button>
              </div>

              {bomRules.map((rule, index) => (
                <Card key={index} className="mb-4">
                  <CardContent className="pt-6">
                    <div className="grid gap-4">
                      <div className="grid grid-cols-3 gap-4">
                        <div className="space-y-2">
                          <Label>부품명 *</Label>
                          <Input
                            value={rule.partName}
                            onChange={(e) => handleUpdateBOMRule(index, 'partName', e.target.value)}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label>부품코드</Label>
                          <Input
                            value={rule.partCode || ""}
                            onChange={(e) => handleUpdateBOMRule(index, 'partCode', e.target.value)}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label>단위 *</Label>
                          <Select
                            value={rule.unit}
                            onValueChange={(value) => handleUpdateBOMRule(index, 'unit', value)}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="EA">EA</SelectItem>
                              <SelectItem value="M">M</SelectItem>
                              <SelectItem value="KG">KG</SelectItem>
                              <SelectItem value="M2">M2</SelectItem>
                              <SelectItem value="SET">SET</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label>수량 계산식 *</Label>
                          <Input
                            value={rule.quantityFormula}
                            onChange={(e) => handleUpdateBOMRule(index, 'quantityFormula', e.target.value)}
                            className="font-mono"
                          />
                        </div>
                        <div className="space-y-2">
                          <Label>반올림 규칙</Label>
                          <Select
                            value={rule.roundingRule || 'ceil'}
                            onValueChange={(value: 'ceil' | 'floor' | 'round') => handleUpdateBOMRule(index, 'roundingRule', value)}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="ceil">올림</SelectItem>
                              <SelectItem value="floor">내림</SelectItem>
                              <SelectItem value="round">반올림</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      <div className="space-y-2">
                        <Label>설명</Label>
                        <Input
                          value={rule.description || ""}
                          onChange={(e) => handleUpdateBOMRule(index, 'description', e.target.value)}
                        />
                      </div>

                      <div className="flex justify-end">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => handleRemoveBOMRule(index)}
                          className="text-red-600"
                        >
                          <Trash2 className="h-4 w-4 mr-2" />
                          규칙 삭제
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>

            <div className="space-y-2">
              <Label>수정 사유 *</Label>
              <Textarea
                value={revisionReason}
                onChange={(e) => setRevisionReason(e.target.value)}
                placeholder="수정 사유를 입력하세요."
                rows={2}
                className="border-red-200 focus:border-red-500"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={handleUpdate}>
              수정
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 템플릿 상세 조회 다이얼로그 */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>BOM 템플릿 상세 정보</DialogTitle>
            <DialogDescription>
              템플릿 정보 및 수정 이력을 조회합니다.
            </DialogDescription>
          </DialogHeader>
          {selectedTemplate && (
            <div className="space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-gray-600">템플릿 코드</Label>
                  <p className="font-mono mt-1">{selectedTemplate.templateCode}</p>
                </div>
                <div>
                  <Label className="text-gray-600">제품 타입</Label>
                  <p className="mt-1">{getProductTypeBadge(selectedTemplate.productType)}</p>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-gray-600">템플릿명</Label>
                  <p className="font-medium mt-1">{selectedTemplate.templateName}</p>
                </div>
                <div>
                  <Label className="text-gray-600">제품 모델</Label>
                  <p className="mt-1">{selectedTemplate.productModel || '-'}</p>
                </div>
              </div>

              <div>
                <Label className="text-gray-600">상태</Label>
                <div className="mt-1">
                  {getStatusBadge(selectedTemplate.status)}
                  {selectedTemplate.isFinal && (
                    <Badge className="ml-2 bg-purple-600">최종 확정</Badge>
                  )}
                </div>
              </div>

              <div className="border-t pt-4">
                <Label className="text-gray-600">BOM 계산 규칙</Label>
                <div className="mt-4 space-y-4">
                  {selectedTemplate.bomRules.map((rule, index) => (
                    <Card key={index}>
                      <CardContent className="pt-6">
                        <div className="grid gap-2">
                          <div className="grid grid-cols-3 gap-4">
                            <div>
                              <Label className="text-sm text-gray-500">부품명</Label>
                              <p className="font-medium">{rule.partName}</p>
                            </div>
                            <div>
                              <Label className="text-sm text-gray-500">부품코드</Label>
                              <p className="font-mono text-sm">{rule.partCode || '-'}</p>
                            </div>
                            <div>
                              <Label className="text-sm text-gray-500">단위</Label>
                              <p>{rule.unit}</p>
                            </div>
                          </div>
                          <div>
                            <Label className="text-sm text-gray-500">수량 계산식</Label>
                            <p className="font-mono bg-gray-50 p-2 rounded mt-1">{rule.quantityFormula}</p>
                          </div>
                          {rule.description && (
                            <div>
                              <Label className="text-sm text-gray-500">설명</Label>
                              <p className="text-sm text-gray-600">{rule.description}</p>
                            </div>
                          )}
                          <div className="grid grid-cols-2 gap-4 text-sm text-gray-600">
                            <div>반올림: {rule.roundingRule === 'ceil' ? '올림' : rule.roundingRule === 'floor' ? '내림' : '반올림'}</div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </div>

              {selectedTemplate.revisions && selectedTemplate.revisions.length > 0 && (
                <div className="border-t pt-4">
                  <Label className="text-gray-600">수정 이력</Label>
                  <div className="mt-4 space-y-2">
                    {selectedTemplate.revisions.map((revision) => (
                      <Card key={revision.revisionNumber}>
                        <CardContent className="pt-4">
                          <div className="flex justify-between items-start">
                            <div>
                              <p className="font-medium">{revision.revisionNumber}차 수정</p>
                              <p className="text-sm text-gray-600 mt-1">{revision.revisionReason}</p>
                            </div>
                            <div className="text-right text-sm text-gray-500">
                              <p>{revision.revisionDate}</p>
                              <p>{revision.revisionBy}</p>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsViewDialogOpen(false)}>
              닫기
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}