'use client';

/**
 * 부적합관리 - 상세 뷰 (읽기전용)
 *
 * 상태별 액션 버튼:
 * - RECEIVED: "분석 시작"
 * - ANALYZING: "조치 완료" (원인분석+처리방안 필수)
 * - RESOLVED: "결재상신"
 * - CLOSED: 없음 (읽기전용)
 */

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  FileWarning,
  Info,
  AlertCircle,
  Wrench,
  Package,
  MessageSquare,
  Pencil,
  ArrowRight,
  CheckCircle,
  Send,
  Trash2,
  Loader2,
} from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { FormSection } from '@/components/organisms/FormSection';
import { BadgeSm } from '@/components/atoms/BadgeSm';
import { formatAmount } from '@/lib/utils/amount';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  getNonconformingReport,
  changeNonconformingStatus,
  deleteNonconformingReport,
} from './actions';
import { NonconformingItemTable } from './NonconformingItemTable';
import {
  NC_STATUS_CONFIG,
  NC_TYPE_LABELS,
  type NonconformingDetail as DetailType,
  type NcStatus,
} from './types';
import type { DetailConfig, ActionItem } from '@/components/templates/IntegratedDetailTemplate/types';

const BASE_PATH = '/material/nonconforming-management';

const detailConfig: DetailConfig = {
  title: '부적합 상세',
  description: '부적합 보고서 상세 정보',
  icon: FileWarning,
  basePath: BASE_PATH,
  fields: [],
  actions: {
    showBack: true,
    backLabel: '목록으로',
  },
};

interface Props {
  id: string;
  mode: 'view' | 'edit';
}

function ReadonlyField({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="space-y-1">
      <Label className="text-xs text-muted-foreground">{label}</Label>
      <div className="text-sm min-h-[1.5rem]">{value || '-'}</div>
    </div>
  );
}

export function NonconformingDetailView({ id, mode }: Props) {
  const router = useRouter();
  const [data, setData] = useState<DetailType | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isStatusChanging, setIsStatusChanging] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  const loadData = useCallback(async () => {
    setIsLoading(true);
    const result = await getNonconformingReport(id);
    if (result.success && result.data) {
      setData(result.data as DetailType);
    } else {
      toast.error(result.error || '조회 실패');
      router.push(BASE_PATH);
    }
    setIsLoading(false);
  }, [id, router]);

  useEffect(() => { loadData(); }, [loadData]);

  // 상태 변경
  const handleStatusChange = useCallback(async (newStatus: string) => {
    if (!data) return;
    // ANALYZING → RESOLVED 전이 시 원인분석+처리방안 필수
    if (newStatus === 'RESOLVED') {
      if (!data.cause_analysis || !data.corrective_action) {
        toast.error('원인 분석과 처리 방안을 먼저 입력하세요. 수정 모드에서 입력 후 다시 시도해주세요.');
        return;
      }
    }
    setIsStatusChanging(true);
    try {
      const result = await changeNonconformingStatus(id, newStatus);
      if (result.success) {
        toast.success('상태가 변경되었습니다.');
        loadData();
      } else {
        toast.error(result.error || '상태 변경 실패');
      }
    } catch {
      toast.error('상태 변경 중 오류 발생');
    } finally {
      setIsStatusChanging(false);
    }
  }, [data, id, loadData]);

  // 삭제
  const handleDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const result = await deleteNonconformingReport(id);
      if (result.success) {
        toast.success('삭제되었습니다.');
        router.push(BASE_PATH);
      } else {
        toast.error(result.error || '삭제 실패');
      }
    } catch {
      toast.error('삭제 중 오류 발생');
    } finally {
      setIsDeleting(false);
      setIsDeleteDialogOpen(false);
    }
  }, [id, router]);

  // 상태별 액션 버튼
  const headerActionItems: ActionItem[] = [];
  if (data) {
    const isClosed = data.status === 'CLOSED';
    const hasApproval = data.approval && data.approval.status === 'pending';

    if (!isClosed && !hasApproval) {
      // 수정 버튼
      headerActionItems.push({
        icon: Pencil,
        label: '수정',
        variant: 'outline',
        onClick: () => router.push(`${BASE_PATH}/${id}?mode=edit`),
      });
    }

    // 상태 전이 버튼
    if (data.status === 'RECEIVED') {
      headerActionItems.push({
        icon: ArrowRight,
        label: '분석 시작',
        onClick: () => handleStatusChange('ANALYZING'),
        disabled: isStatusChanging,
        loading: isStatusChanging,
      });
    } else if (data.status === 'ANALYZING') {
      headerActionItems.push({
        icon: CheckCircle,
        label: '조치 완료',
        className: 'bg-blue-600 hover:bg-blue-700 text-white',
        onClick: () => handleStatusChange('RESOLVED'),
        disabled: isStatusChanging,
        loading: isStatusChanging,
      });
    } else if (data.status === 'RESOLVED' && !hasApproval) {
      headerActionItems.push({
        icon: Send,
        label: '결재상신',
        className: 'bg-green-600 hover:bg-green-700 text-white',
        onClick: () => {
          toast.info('결재상신 기능은 결재 시스템 연동 후 활성화됩니다.');
        },
      });
    }

    // 삭제 (CLOSED가 아닌 경우)
    if (!isClosed) {
      headerActionItems.push({
        icon: Trash2,
        label: '삭제',
        variant: 'destructive',
        onClick: () => setIsDeleteDialogOpen(true),
      });
    }
  }

  // 비용 계산
  const materialCost = data?.items?.reduce((sum, item) => sum + (item.amount || 0), 0) ?? 0;

  return (
    <>
      <IntegratedDetailTemplate
        config={detailConfig}
        mode="view"
        isLoading={isLoading}
        initialData={data as unknown as Record<string, unknown>}
        onBack={() => router.push(BASE_PATH)}
        headerActionItems={headerActionItems}
        headerActions={
          data ? (
            <BadgeSm className={NC_STATUS_CONFIG[data.status].className}>
              {NC_STATUS_CONFIG[data.status].label}
            </BadgeSm>
          ) : null
        }
        renderView={() =>
          data ? (
            <div className="space-y-6">
              {/* 섹션 1: 기본 정보 */}
              <FormSection title="기본 정보" icon={Info}>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <ReadonlyField label="부적합번호" value={
                    <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
                      {data.nc_number}
                    </code>
                  } />
                  <ReadonlyField label="부적합 유형" value={NC_TYPE_LABELS[data.nc_type]} />
                  <ReadonlyField label="발생일" value={data.occurred_at} />
                  <ReadonlyField label="불량확인일" value={data.confirmed_at} />
                  <ReadonlyField label="현장명" value={data.site_name} />
                  <ReadonlyField label="부서" value={data.department?.name} />
                  <ReadonlyField label="관련 수주" value={data.order?.order_number} />
                  <ReadonlyField label="등록자" value={data.creator?.name} />
                  <ReadonlyField label="관련 직원" value={data.related_employee?.name} />
                  <ReadonlyField label="단위" value={data.unit} />
                </div>
              </FormSection>

              {/* 섹션 2: 불량 내역 */}
              <FormSection title="불량 내역" icon={AlertCircle} variant="highlighted">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <ReadonlyField label="관련 품목" value={data.item?.name} />
                  <ReadonlyField label="불량 수량" value={data.defect_quantity} />
                </div>
                <div className="mt-4">
                  <ReadonlyField label="불량 상세 설명" value={
                    data.defect_description ? (
                      <p className="whitespace-pre-wrap text-sm">{data.defect_description}</p>
                    ) : null
                  } />
                </div>
              </FormSection>

              {/* 섹션 3: 원인 분석 및 처리 방안 */}
              <FormSection title="원인 분석 및 처리 방안" icon={Wrench} variant="highlighted">
                <div className="space-y-4">
                  <ReadonlyField label="불량 발생 원인 및 분석" value={
                    data.cause_analysis ? (
                      <p className="whitespace-pre-wrap text-sm">{data.cause_analysis}</p>
                    ) : null
                  } />
                  <ReadonlyField label="처리 방안 및 개선 사항" value={
                    data.corrective_action ? (
                      <p className="whitespace-pre-wrap text-sm">{data.corrective_action}</p>
                    ) : null
                  } />
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <ReadonlyField label="조치 완료일" value={data.action_completed_at} />
                    <ReadonlyField label="조치 담당자" value={data.action_manager?.name} />
                  </div>
                </div>
              </FormSection>

              {/* 섹션 4: 자재 내역 및 비용 */}
              <FormSection title="자재 내역 및 비용" icon={Package} variant="highlighted">
                <NonconformingItemTable items={data.items || []} onChange={() => {}} disabled />

                {/* 비용 요약 */}
                <div className="mt-6 border rounded-md p-4 bg-muted/30">
                  <h4 className="text-sm font-semibold mb-3">비용 요약</h4>
                  <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                    <ReadonlyField label="자재 비용" value={formatAmount(materialCost)} />
                    <ReadonlyField label="운송 비용" value={formatAmount(data.shipping_cost)} />
                    <ReadonlyField label="시공 비용" value={formatAmount(data.construction_cost)} />
                    <ReadonlyField label="기타 비용" value={formatAmount(data.other_cost)} />
                    <div className="space-y-1">
                      <Label className="text-xs text-muted-foreground font-bold">비용 합계</Label>
                      <div className="text-sm font-bold text-blue-700">
                        {formatAmount(data.total_cost)}
                      </div>
                    </div>
                  </div>
                </div>
              </FormSection>

              {/* 섹션 5: 비고 */}
              <FormSection title="비고" icon={MessageSquare}>
                <div className="space-y-4">
                  <ReadonlyField label="비고" value={
                    data.remarks ? <p className="whitespace-pre-wrap text-sm">{data.remarks}</p> : null
                  } />
                  <ReadonlyField label="도면 저장 위치" value={data.drawing_location} />
                </div>
              </FormSection>

              {/* 결재 정보 */}
              {data.approval && (
                <FormSection title="결재 정보" icon={Send}>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <ReadonlyField label="결재번호" value={data.approval.document_number} />
                    <ReadonlyField label="결재상태" value={data.approval.status} />
                    <ReadonlyField label="완료일" value={data.approval.completed_at} />
                  </div>
                  {data.approval.steps?.length > 0 && (
                    <div className="mt-3">
                      <Label className="text-xs text-muted-foreground">결재선</Label>
                      <div className="flex gap-2 mt-1">
                        {data.approval.steps.map((step) => (
                          <BadgeSm
                            key={step.id}
                            className={
                              step.status === 'approved'
                                ? 'bg-green-100 text-green-700'
                                : step.status === 'rejected'
                                  ? 'bg-red-100 text-red-700'
                                  : 'bg-gray-100 text-gray-700'
                            }
                          >
                            {step.approver?.name} ({step.step_type})
                          </BadgeSm>
                        ))}
                      </div>
                    </div>
                  )}
                </FormSection>
              )}
            </div>
          ) : null
        }
      />

      <DeleteConfirmDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        onConfirm={handleDelete}
        title="부적합 보고서 삭제"
        description="이 부적합 보고서를 삭제하시겠습니까? 삭제된 보고서는 복구할 수 없습니다."
        loading={isDeleting}
      />
    </>
  );
}
