import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { CheckCircle, XCircle, AlertCircle } from "lucide-react";
import { useMemo } from "react";
import { useData } from "../contexts/DataContext";

export function QualityStatusWidget() {
  const { qualityInspections } = useData();

  // 실제 데이터로부터 품질 현황 계산
  const qualityData = useMemo(() => {
    const total = qualityInspections.reduce((sum, insp) => sum + insp.quantity, 0);
    const passed = qualityInspections.reduce((sum, insp) => sum + insp.passQuantity, 0);
    const failed = qualityInspections.reduce((sum, insp) => sum + insp.failQuantity, 0);
    const defectRate = total > 0 ? (failed / total) * 100 : 0;

    // 검사 유형별 불량률
    const byProcess = ['incoming', 'process', 'final'].map(type => {
      const typeInspections = qualityInspections.filter(insp => insp.inspectionType === type);
      const typeTotal = typeInspections.reduce((sum, insp) => sum + insp.quantity, 0);
      const typeFailed = typeInspections.reduce((sum, insp) => sum + insp.failQuantity, 0);
      const rate = typeTotal > 0 ? (typeFailed / typeTotal) * 100 : 0;
      
      const nameMap: Record<string, string> = {
        'incoming': '입고검사',
        'process': '공정검사',
        'final': '최종검사'
      };
      
      return { name: nameMap[type], rate: Math.round(rate * 10) / 10 };
    });

    return {
      overall: {
        defectRate: Math.round(defectRate * 10) / 10,
        targetRate: 3.0
      },
      inspectionSummary: {
        total,
        passed,
        failed
      },
      byProcess
    };
  }, [qualityInspections]);

  return (
    <Card className="h-full">
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2">
          <CheckCircle className="h-5 w-5 text-green-600" />
          품질 현황
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 전체 불량률 */}
          <div className="p-4 bg-gradient-to-r from-green-50 to-green-100 dark:from-green-950/30 dark:to-green-900/30 rounded-lg border border-green-200/50 dark:border-green-800/50">
            <div className="text-sm text-green-700 dark:text-green-400 mb-1">전체 불량률</div>
            <div className="text-3xl font-bold text-green-900 dark:text-green-100">
              {qualityData.overall.defectRate}%
            </div>
            <div className="text-sm text-green-600 dark:text-green-300 mt-1">
              목표: {qualityData.overall.targetRate}% 이하
            </div>
          </div>

          {/* 검사 현황 */}
          <div className="grid grid-cols-3 gap-2">
            <div className="text-center p-3 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200/50 dark:border-blue-800/50">
              <div className="text-xs text-blue-700 dark:text-blue-400 mb-1">검사</div>
              <div className="text-lg font-bold text-blue-900 dark:text-blue-100">
                {qualityData.inspectionSummary.total}
              </div>
            </div>
            <div className="text-center p-3 bg-green-50 dark:bg-green-950/30 rounded-lg border border-green-200/50 dark:border-green-800/50">
              <div className="text-xs text-green-700 dark:text-green-400 mb-1">합격</div>
              <div className="text-lg font-bold text-green-900 dark:text-green-100">
                {qualityData.inspectionSummary.passed}
              </div>
            </div>
            <div className="text-center p-3 bg-red-50 dark:bg-red-950/30 rounded-lg border border-red-200/50 dark:border-red-800/50">
              <div className="text-xs text-red-700 dark:text-red-400 mb-1">불량</div>
              <div className="text-lg font-bold text-red-900 dark:text-red-100">
                {qualityData.inspectionSummary.failed}
              </div>
            </div>
          </div>

          {/* 공정별 불량률 */}
          <div className="space-y-2">
            <div className="text-sm font-semibold">공정별 불량률</div>
            {qualityData.byProcess.map((process: any, index: number) => (
              <div key={index} className="flex items-center justify-between p-2 bg-muted/50 dark:bg-muted/30 rounded border border-border/50">
                <span className="text-sm">{process.name}</span>
                <div className="flex items-center gap-2">
                  {process.rate > 3 && <AlertCircle className="h-4 w-4 text-red-500 dark:text-red-400" />}
                  <Badge variant={process.rate <= 3 ? "default" : "destructive"}>
                    {process.rate}%
                  </Badge>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}