'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { List, Edit, Wrench, Package, ArrowLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { ProcessWorkLogPreviewModal } from './ProcessWorkLogPreviewModal';
import { useMenuStore } from '@/store/menuStore';
import type { Process } from '@/types/process';
import { MATCHING_TYPE_OPTIONS } from '@/types/process';

interface ProcessDetailProps {
  process: Process;
}

export function ProcessDetail({ process }: ProcessDetailProps) {
  const router = useRouter();
  const [workLogModalOpen, setWorkLogModalOpen] = useState(false);
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  // 패턴 규칙과 개별 품목 분리
  const { patternRules, individualItems } = useMemo(() => {
    const patterns = process.classificationRules.filter(
      (rule) => rule.registrationType === 'pattern'
    );
    const individuals = process.classificationRules.filter(
      (rule) => rule.registrationType === 'individual'
    );
    return { patternRules: patterns, individualItems: individuals };
  }, [process.classificationRules]);

  // 매칭 타입 라벨
  const getMatchingTypeLabel = (type: string) => {
    const option = MATCHING_TYPE_OPTIONS.find((opt) => opt.value === type);
    return option?.label || type;
  };

  const handleEdit = () => {
    router.push(`/ko/master-data/process-management/${process.id}?mode=edit`);
  };

  const handleList = () => {
    router.push('/ko/master-data/process-management');
  };

  const handleViewWorkLog = () => {
    setWorkLogModalOpen(true);
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title="공정 상세"
        icon={Wrench}
      />

      <div className="space-y-6 pb-24">
        {/* 기본 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {/* 반응형 6열 그리드: PC 6열, 태블릿 4열, 작은태블릿 2열, 모바일 1열 */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
              <div className="space-y-1 lg:col-span-2">
                <div className="text-sm text-muted-foreground">공정코드</div>
                <div className="font-medium">{process.processCode}</div>
              </div>
              <div className="space-y-1 lg:col-span-2">
                <div className="text-sm text-muted-foreground">공정명</div>
                <div className="font-medium">{process.processName}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">공정구분</div>
                <Badge variant="secondary">{process.processType}</Badge>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">담당부서</div>
                <div className="font-medium">{process.department}</div>
              </div>
              <div className="space-y-1 lg:col-span-2">
                <div className="text-sm text-muted-foreground">작업일지 양식</div>
                <div className="flex items-center gap-2">
                  <span className="font-medium">
                    {process.workLogTemplate || '-'}
                  </span>
                  {process.workLogTemplate && (
                    <Button variant="outline" size="sm" onClick={handleViewWorkLog}>
                      양식 보기
                    </Button>
                  )}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 등록 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">등록 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
              <div className="space-y-1 lg:col-span-3">
                <div className="text-sm text-muted-foreground">등록일</div>
                <div className="font-medium">{process.createdAt}</div>
              </div>
              <div className="space-y-1 lg:col-span-3">
                <div className="text-sm text-muted-foreground">최종수정일</div>
                <div className="font-medium">{process.updatedAt}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 자동 분류 규칙 (패턴 기반) */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base flex items-center gap-2">
              <Wrench className="h-4 w-4" />
              자동 분류 규칙
            </CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {patternRules.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Wrench className="h-10 w-10 mx-auto mb-3 opacity-30" />
                <p className="text-sm">등록된 자동 분류 규칙이 없습니다</p>
              </div>
            ) : (
              <div className="space-y-3">
                {patternRules.map((rule) => (
                  <div
                    key={rule.id}
                    className="flex items-center justify-between p-4 border rounded-lg"
                  >
                    <div className="flex items-center gap-4">
                      <Badge variant={rule.isActive ? 'default' : 'secondary'}>
                        {rule.isActive ? '활성' : '비활성'}
                      </Badge>
                      <div>
                        <div className="font-medium">
                          {rule.ruleType} · {getMatchingTypeLabel(rule.matchingType)} · "{rule.conditionValue}"
                        </div>
                        {rule.description && (
                          <div className="text-sm text-muted-foreground">
                            {rule.description}
                          </div>
                        )}
                      </div>
                    </div>
                    <Badge variant="outline">우선순위: {rule.priority}</Badge>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 개별 품목 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base flex items-center gap-2">
              <Package className="h-4 w-4" />
              개별 품목
              {individualItems.length > 0 && individualItems[0].items && (
                <Badge variant="secondary" className="ml-2">
                  {individualItems[0].items.length}개
                </Badge>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {individualItems.length === 0 || !individualItems[0].items?.length ? (
              <div className="text-center py-8 text-muted-foreground">
                <Package className="h-10 w-10 mx-auto mb-3 opacity-30" />
                <p className="text-sm">등록된 개별 품목이 없습니다</p>
              </div>
            ) : (
              <div className="max-h-80 overflow-y-auto">
                <div className="space-y-2">
                  {individualItems[0].items.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-center justify-between p-3 border rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors"
                    >
                      <div className="flex items-center gap-3">
                        <Badge variant="outline" className="font-mono text-xs">
                          {item.code}
                        </Badge>
                        <span className="font-medium">{item.name}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 세부 작업단계 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">세부 작업단계</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            {process.workSteps.length > 0 ? (
              <div className="flex items-center gap-2 flex-wrap">
                {process.workSteps.map((step, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <Badge
                      variant="outline"
                      className="px-3 py-1.5 bg-muted/50"
                    >
                      <span className="bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs mr-2">
                        {index + 1}
                      </span>
                      {step}
                    </Badge>
                    {index < process.workSteps.length - 1 && (
                      <span className="text-muted-foreground">{'>'}</span>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-muted-foreground">-</div>
            )}
          </CardContent>
        </Card>

        {/* 작업 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">작업 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-6">
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">필요인원</div>
                <div className="font-medium">{process.requiredWorkers}명</div>
              </div>
              <div className="space-y-1 lg:col-span-2">
                <div className="text-sm text-muted-foreground">설비정보</div>
                <div className="font-medium">{process.equipmentInfo || '-'}</div>
              </div>
              <div className="space-y-1 lg:col-span-3">
                <div className="text-sm text-muted-foreground">설명</div>
                <div className="font-medium">{process.description || '-'}</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 하단 액션 버튼 (sticky) */}
      <div className={`fixed bottom-6 ${sidebarCollapsed ? 'left-[156px]' : 'left-[316px]'} right-[48px] px-6 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 flex items-center justify-between`}>
        <Button variant="outline" onClick={handleList}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          목록으로
        </Button>
        <Button onClick={handleEdit}>
          <Edit className="h-4 w-4 mr-2" />
          수정
        </Button>
      </div>

      {/* 작업일지 양식 미리보기 모달 */}
      <ProcessWorkLogPreviewModal
        open={workLogModalOpen}
        onOpenChange={setWorkLogModalOpen}
        process={process}
      />
    </PageLayout>
  );
}