'use client';

/**
 * 설비 상세 페이지
 *
 * 3탭 구성: 기본정보, 점검항목, 수리이력
 * URL: /quality/equipment/[id]
 * 수정: /quality/equipment/[id]?mode=edit
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  ArrowLeft,
  Pencil,
  Save,
  X,
  Trash2,
  Loader2,
  Wrench,
  ClipboardList,
  History,
  Plus,
  Copy,
  Download,
  Printer,
  ImagePlus,
} from 'lucide-react';
import { toast } from 'sonner';
import { QRCodeCanvas } from 'qrcode.react';
import { useMenuStore } from '@/stores/menuStore';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Checkbox } from '@/components/ui/checkbox';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { FormField } from '@/components/molecules/FormField';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  getEquipmentDetail,
  updateEquipment,
  deleteEquipment,
  getEquipmentOptions,
  getInspectionTemplates,
  createInspectionTemplate,
  deleteInspectionTemplate,
  copyInspectionTemplates,
  getRepairList,
  getManagerOptions,
  uploadEquipmentPhoto,
  deleteEquipmentPhoto,
} from './actions';
import type {
  Equipment,
  EquipmentFormData,
  EquipmentOptions,
  InspectionTemplate,
  InspectionTemplateFormData,
  InspectionCycle,
  EquipmentRepair,
  ManagerOption,
} from './types';
import {
  EQUIPMENT_STATUS_LABEL,
  EQUIPMENT_STATUS_COLOR,
  INSPECTION_CYCLE_LABEL,
  INSPECTION_CYCLES,
  REPAIR_TYPE_LABEL,
} from './types';

// ===== QR 코드 URL 생성 =====
const QR_BASE_URL = typeof window !== 'undefined'
  ? `${window.location.protocol}//${window.location.host}`
  : 'https://admin.codebridge-x.com';

interface EquipmentDetailProps {
  id: string;
}

export function EquipmentDetail({ id }: EquipmentDetailProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const initialMode = searchParams.get('mode') === 'edit' ? 'edit' : 'view';

  const [equipment, setEquipment] = useState<Equipment | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [mode, setMode] = useState<'view' | 'edit'>(initialMode);
  const [activeTab, setActiveTab] = useState('info');

  // 수정 폼 상태
  const [formData, setFormData] = useState<EquipmentFormData | null>(null);
  const [options, setOptions] = useState<EquipmentOptions | null>(null);
  const [managers, setManagers] = useState<ManagerOption[]>([]);
  const [isSaving, setIsSaving] = useState(false);

  // 삭제
  const [showDelete, setShowDelete] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // 점검항목 탭
  const [selectedCycle, setSelectedCycle] = useState<InspectionCycle>('daily');
  const [templates, setTemplates] = useState<InspectionTemplate[]>([]);
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);
  const [showAddTemplate, setShowAddTemplate] = useState(false);
  const [showCopyDialog, setShowCopyDialog] = useState(false);
  const [copyTargetCycles, setCopyTargetCycles] = useState<InspectionCycle[]>([]);
  const [newTemplate, setNewTemplate] = useState<InspectionTemplateFormData>({
    inspectionCycle: 'daily',
    itemNo: '',
    checkPoint: '',
    checkItem: '',
    checkTiming: '',
    checkFrequency: '',
    checkMethod: '',
  });

  // 수리이력 탭
  const [repairs, setRepairs] = useState<EquipmentRepair[]>([]);
  const [isLoadingRepairs, setIsLoadingRepairs] = useState(false);

  // 사진 업로드
  const [isUploading, setIsUploading] = useState(false);
  const photoInputRef = useRef<HTMLInputElement>(null);

  // QR 코드 ref
  const qrRef = useRef<HTMLDivElement>(null);

  // 데이터 로드
  const loadEquipment = useCallback(async () => {
    setIsLoading(true);
    const result = await getEquipmentDetail(id);
    if (result.success && result.data) {
      setEquipment(result.data);
    } else {
      toast.error(result.error || '설비 데이터를 불러올 수 없습니다.');
      router.push('/quality/equipment');
    }
    setIsLoading(false);
  }, [id, router]);

  useEffect(() => {
    loadEquipment();
    getEquipmentOptions().then((r) => {
      if (r.success && r.data) setOptions(r.data);
    });
    getManagerOptions().then((mgrs) => setManagers(mgrs));
  }, [loadEquipment]);

  // 점검항목 로드
  const loadTemplates = useCallback(async () => {
    setIsLoadingTemplates(true);
    const result = await getInspectionTemplates(id, selectedCycle);
    if (result.success && result.data) {
      setTemplates(result.data);
    }
    setIsLoadingTemplates(false);
  }, [id, selectedCycle]);

  useEffect(() => {
    if (activeTab === 'inspection') {
      loadTemplates();
    }
  }, [activeTab, loadTemplates]);

  // 수리이력 로드
  const loadRepairs = useCallback(async () => {
    setIsLoadingRepairs(true);
    const result = await getRepairList({ equipmentId: id, perPage: 100 });
    if (result.success) {
      setRepairs(result.data);
    }
    setIsLoadingRepairs(false);
  }, [id]);

  useEffect(() => {
    if (activeTab === 'repairs') {
      loadRepairs();
    }
  }, [activeTab, loadRepairs]);

  // 수정 모드 진입
  const enterEditMode = useCallback(() => {
    if (!equipment) return;
    setFormData({
      equipmentCode: equipment.equipmentCode,
      name: equipment.name,
      equipmentType: equipment.equipmentType,
      specification: equipment.specification,
      manufacturer: equipment.manufacturer,
      modelName: equipment.modelName,
      serialNo: equipment.serialNo,
      location: equipment.location,
      productionLine: equipment.productionLine,
      purchaseDate: equipment.purchaseDate,
      installDate: equipment.installDate,
      purchasePrice: equipment.purchasePrice,
      usefulLife: equipment.usefulLife ? String(equipment.usefulLife) : '',
      status: equipment.status,
      managerId: equipment.managerId ? String(equipment.managerId) : '',
      subManagerId: equipment.subManagerId ? String(equipment.subManagerId) : '',
      memo: equipment.memo,
    });
    setMode('edit');
  }, [equipment]);

  // URL ?mode=edit로 직접 진입 시 equipment 로드 후 formData 자동 설정
  useEffect(() => {
    if (equipment && mode === 'edit' && !formData) {
      enterEditMode();
    }
  }, [equipment, mode, formData, enterEditMode]);

  const cancelEdit = useCallback(() => {
    setMode('view');
    setFormData(null);
  }, []);

  const handleFormChange = useCallback((field: keyof EquipmentFormData, value: string) => {
    setFormData((prev) => prev ? { ...prev, [field]: value } : prev);
  }, []);

  const handleSave = useCallback(async () => {
    if (!formData) return;
    if (!formData.equipmentCode.trim() || !formData.name.trim()) {
      toast.error('설비코드와 설비명은 필수입니다.');
      return;
    }
    setIsSaving(true);
    try {
      const result = await updateEquipment(id, formData);
      if (result.success) {
        toast.success('설비가 수정되었습니다.');
        setMode('view');
        setFormData(null);
        await loadEquipment();
      } else {
        toast.error(result.error || '수정에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  }, [id, formData, loadEquipment]);

  const handleDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      const result = await deleteEquipment(id);
      if (result.success) {
        toast.success('설비가 삭제되었습니다.');
        router.push('/quality/equipment');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsDeleting(false);
      setShowDelete(false);
    }
  }, [id, router]);

  // 점검항목 추가
  const handleAddTemplate = useCallback(async () => {
    if (!newTemplate.checkPoint.trim() || !newTemplate.checkItem.trim()) {
      toast.error('점검개소와 점검항목을 입력하세요.');
      return;
    }
    const result = await createInspectionTemplate(id, {
      ...newTemplate,
      inspectionCycle: selectedCycle,
    });
    if (result.success) {
      toast.success('점검항목이 추가되었습니다.');
      setShowAddTemplate(false);
      setNewTemplate({
        inspectionCycle: selectedCycle,
        itemNo: '',
        checkPoint: '',
        checkItem: '',
        checkTiming: '',
        checkFrequency: '',
        checkMethod: '',
      });
      await loadTemplates();
    } else {
      toast.error(result.error || '추가에 실패했습니다.');
    }
  }, [id, selectedCycle, newTemplate, loadTemplates]);

  const handleDeleteTemplate = useCallback(async (templateId: number) => {
    const result = await deleteInspectionTemplate(templateId);
    if (result.success) {
      toast.success('점검항목이 삭제되었습니다.');
      await loadTemplates();
    } else {
      toast.error(result.error || '삭제에 실패했습니다.');
    }
  }, [loadTemplates]);

  // 점검항목 복사
  const handleCopyTemplates = useCallback(async () => {
    if (copyTargetCycles.length === 0) {
      toast.error('복사할 주기를 선택하세요.');
      return;
    }
    const result = await copyInspectionTemplates(id, selectedCycle, copyTargetCycles);
    if (result.success) {
      toast.success('점검항목이 복사되었습니다.');
      setShowCopyDialog(false);
      setCopyTargetCycles([]);
    } else {
      toast.error(result.error || '복사에 실패했습니다.');
    }
  }, [id, selectedCycle, copyTargetCycles]);

  // QR 코드 다운로드
  const handleQRDownload = useCallback(() => {
    const canvas = qrRef.current?.querySelector('canvas');
    if (!canvas) return;
    const url = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = `${equipment?.equipmentCode || 'qr'}.png`;
    link.href = url;
    link.click();
  }, [equipment]);

  // QR 코드 인쇄
  const handleQRPrint = useCallback(() => {
    const canvas = qrRef.current?.querySelector('canvas');
    if (!canvas) return;
    const url = canvas.toDataURL('image/png');
    const win = window.open('', '_blank');
    if (!win) return;
    win.document.write(`
      <html><head><title>QR 코드 인쇄</title></head>
      <body style="display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;">
        <div style="text-align:center;">
          <img src="${url}" style="width:200px;height:200px;" onload="window.print();" />
          <p style="font-weight:bold;margin-top:12px;">${equipment?.equipmentCode}</p>
          <p>${equipment?.name}</p>
        </div>
      </body></html>
    `);
    win.document.close();
  }, [equipment]);

  // 사진 업로드
  const handlePhotoUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setIsUploading(true);
    try {
      const result = await uploadEquipmentPhoto(id, file);
      if (result.success) {
        toast.success('사진이 업로드되었습니다.');
        await loadEquipment();
      } else {
        toast.error(result.error || '사진 업로드에 실패했습니다.');
      }
    } finally {
      setIsUploading(false);
      if (photoInputRef.current) photoInputRef.current.value = '';
    }
  }, [id, loadEquipment]);

  // 사진 삭제
  const handlePhotoDelete = useCallback(async (fileId: number) => {
    const result = await deleteEquipmentPhoto(id, fileId);
    if (result.success) {
      toast.success('사진이 삭제되었습니다.');
      await loadEquipment();
    } else {
      toast.error(result.error || '사진 삭제에 실패했습니다.');
    }
  }, [id, loadEquipment]);

  if (isLoading || !equipment) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const qrUrl = `${QR_BASE_URL}/quality/equipment-inspections?equipment_id=${equipment.id}`;

  const InfoRow = ({ label, value }: { label: string; value: string | number | null }) => (
    <div className="flex flex-col">
      <span className="text-sm text-muted-foreground">{label}</span>
      <span className="text-sm font-medium">{value || '-'}</span>
    </div>
  );

  return (
    <div className="space-y-6 p-3 md:p-6 pb-24">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            onClick={() => router.push('/quality/equipment')}
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-xl font-bold">{equipment.name}</h1>
              <Badge className={EQUIPMENT_STATUS_COLOR[equipment.status]} variant="secondary">
                {EQUIPMENT_STATUS_LABEL[equipment.status]}
              </Badge>
            </div>
            <p className="text-sm text-muted-foreground">{equipment.equipmentCode}</p>
          </div>
        </div>
      </div>

      {/* 탭 */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          <TabsTrigger value="info">기본정보</TabsTrigger>
          <TabsTrigger value="inspection">점검항목</TabsTrigger>
          <TabsTrigger value="repairs">수리이력</TabsTrigger>
        </TabsList>

        {/* ==================== 기본정보 탭 ==================== */}
        <TabsContent value="info" className="space-y-4">
          {mode === 'view' ? (
            <>
              {/* 기본정보 */}
              <Card>
                <CardHeader><CardTitle className="text-base">기본정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <InfoRow label="설비코드" value={equipment.equipmentCode} />
                    <InfoRow label="설비명" value={equipment.name} />
                    <InfoRow label="설비유형" value={equipment.equipmentType} />
                    <InfoRow label="규격" value={equipment.specification} />
                  </div>
                </CardContent>
              </Card>

              {/* 제조사 정보 */}
              <Card>
                <CardHeader><CardTitle className="text-base">제조사 정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                    <InfoRow label="제조사" value={equipment.manufacturer} />
                    <InfoRow label="모델명" value={equipment.modelName} />
                    <InfoRow label="제조번호" value={equipment.serialNo} />
                  </div>
                </CardContent>
              </Card>

              {/* 설치 정보 */}
              <Card>
                <CardHeader><CardTitle className="text-base">설치 정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <InfoRow label="위치" value={equipment.location} />
                    <InfoRow label="생산라인" value={equipment.productionLine} />
                    <InfoRow label="구입일" value={equipment.purchaseDate} />
                    <InfoRow label="설치일" value={equipment.installDate} />
                    <InfoRow label="구입가격" value={equipment.purchasePrice} />
                    <InfoRow label="내용연수" value={equipment.usefulLife ? `${equipment.usefulLife}년` : null} />
                    <InfoRow label="관리자 정" value={equipment.managerName} />
                    <InfoRow label="관리자 부" value={equipment.subManagerName} />
                  </div>
                  <div className="mt-4">
                    <span className="text-sm text-muted-foreground">상태</span>
                    <div className="mt-1">
                      <Badge className={EQUIPMENT_STATUS_COLOR[equipment.status]} variant="secondary">
                        {EQUIPMENT_STATUS_LABEL[equipment.status]}
                      </Badge>
                    </div>
                  </div>
                  {equipment.memo && (
                    <div className="mt-4">
                      <span className="text-sm text-muted-foreground">비고</span>
                      <p className="text-sm mt-1 whitespace-pre-wrap">{equipment.memo}</p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 설비 사진 */}
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base">설비 사진</CardTitle>
                    <div>
                      <input
                        ref={photoInputRef}
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handlePhotoUpload}
                      />
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => photoInputRef.current?.click()}
                        disabled={isUploading || equipment.photos.length >= 10}
                      >
                        {isUploading ? (
                          <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                        ) : (
                          <ImagePlus className="h-4 w-4 mr-1" />
                        )}
                        사진 추가
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  {equipment.photos.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      등록된 사진이 없습니다.
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {equipment.photos.map((photo) => (
                        <div key={photo.id} className="space-y-2">
                          <div className="relative border rounded-lg overflow-hidden bg-gray-50 group">
                            {/* eslint-disable-next-line @next/next/no-img-element */}
                            <img
                              src={`/api/proxy/files/${photo.id}/download`}
                              alt={photo.displayName}
                              className="w-full h-auto max-h-[400px] object-contain"
                            />
                            <Button
                              variant="destructive"
                              size="sm"
                              className="absolute top-2 right-2 h-7 px-2 opacity-0 group-hover:opacity-100 transition-opacity"
                              onClick={() => handlePhotoDelete(photo.id)}
                            >
                              <Trash2 className="h-3.5 w-3.5 mr-1" />
                              삭제
                            </Button>
                          </div>
                          <p className="text-xs text-muted-foreground">{photo.displayName}</p>
                        </div>
                      ))}
                    </div>
                  )}
                  {equipment.photos.length >= 10 && (
                    <p className="text-xs text-muted-foreground mt-2">최대 10장까지 등록 가능합니다.</p>
                  )}
                </CardContent>
              </Card>

              {/* QR 코드 */}
              <Card>
                <CardHeader><CardTitle className="text-base">QR 코드 (모바일 점검)</CardTitle></CardHeader>
                <CardContent>
                  <div className="flex flex-col items-center gap-4 md:flex-row md:items-start md:gap-6">
                    <div ref={qrRef} className="border rounded-lg p-3 bg-white shrink-0">
                      <QRCodeCanvas value={qrUrl} size={120} />
                    </div>
                    <div className="space-y-2 text-center md:text-left">
                      <p className="text-sm font-medium">{equipment.equipmentCode}</p>
                      <p className="text-sm">{equipment.name}</p>
                      <p className="text-xs text-muted-foreground break-all">{qrUrl}</p>
                      <div className="flex gap-2 pt-2 justify-center md:justify-start">
                        <Button variant="outline" size="sm" onClick={handleQRDownload}>
                          <Download className="h-3.5 w-3.5 mr-1" />
                          PNG 다운로드
                        </Button>
                        <Button variant="outline" size="sm" onClick={handleQRPrint}>
                          <Printer className="h-3.5 w-3.5 mr-1" />
                          인쇄
                        </Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </>
          ) : formData && (
            /* 수정 모드 */
            <>
              <Card>
                <CardHeader><CardTitle className="text-base">기본정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField label="설비코드" required value={formData.equipmentCode} onChange={(v) => handleFormChange('equipmentCode', v)} placeholder="KD-M-001" />
                    <FormField label="설비명" required value={formData.name} onChange={(v) => handleFormChange('name', v)} placeholder="포밍기#1" />
                    <div>
                      <Label>설비유형</Label>
                      <div className="mt-1">
                        <Select value={formData.equipmentType || '_none'} onValueChange={(v) => handleFormChange('equipmentType', v === '_none' ? '' : v)}>
                          <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="_none">선택</SelectItem>
                            {(options?.equipmentTypes || []).map((type) => (
                              <SelectItem key={type} value={type}>{type}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <FormField label="규격" value={formData.specification} onChange={(v) => handleFormChange('specification', v)} />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader><CardTitle className="text-base">제조사 정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <FormField label="제조사" value={formData.manufacturer} onChange={(v) => handleFormChange('manufacturer', v)} />
                    <FormField label="모델명" value={formData.modelName} onChange={(v) => handleFormChange('modelName', v)} />
                    <FormField label="제조번호" value={formData.serialNo} onChange={(v) => handleFormChange('serialNo', v)} />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader><CardTitle className="text-base">설치 정보</CardTitle></CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField label="위치" value={formData.location} onChange={(v) => handleFormChange('location', v)} placeholder="1공장-1F" />
                    <div>
                      <Label>생산라인</Label>
                      <div className="mt-1">
                        <Select value={formData.productionLine || '_none'} onValueChange={(v) => handleFormChange('productionLine', v === '_none' ? '' : v)}>
                          <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                          <SelectContent>
                            <SelectItem value="_none">선택</SelectItem>
                            {(options?.productionLines || []).map((line) => (
                              <SelectItem key={line} value={line}>{line}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <FormField label="구입일" type="date" value={formData.purchaseDate} onChange={(v) => handleFormChange('purchaseDate', v)} />
                    <FormField label="설치일" type="date" value={formData.installDate} onChange={(v) => handleFormChange('installDate', v)} />
                    <FormField label="구입가격 (원)" type="number" value={formData.purchasePrice} onChange={(v) => handleFormChange('purchasePrice', v)} />
                    <FormField label="내용연수 (년)" type="number" value={formData.usefulLife} onChange={(v) => handleFormChange('usefulLife', v)} />
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader><CardTitle className="text-base">관리자 / 비고</CardTitle></CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label>관리자 정</Label>
                        <div className="mt-1">
                          <Select value={formData.managerId || '_none'} onValueChange={(v) => handleFormChange('managerId', v === '_none' ? '' : v)}>
                            <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                            <SelectContent>
                              <SelectItem value="_none">선택</SelectItem>
                              {managers.map((mgr) => (
                                <SelectItem key={mgr.id} value={mgr.id}>
                                  {mgr.department ? `${mgr.department} / ` : ''}{mgr.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                      <div>
                        <Label>관리자 부</Label>
                        <div className="mt-1">
                          <Select value={formData.subManagerId || '_none'} onValueChange={(v) => handleFormChange('subManagerId', v === '_none' ? '' : v)}>
                            <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                            <SelectContent>
                              <SelectItem value="_none">선택</SelectItem>
                              {managers.map((mgr) => (
                                <SelectItem key={mgr.id} value={mgr.id}>
                                  {mgr.department ? `${mgr.department} / ` : ''}{mgr.name}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    </div>
                    <div>
                      <Label>상태</Label>
                      <div className="mt-1">
                        <Select value={formData.status} onValueChange={(v) => handleFormChange('status', v)}>
                          <SelectTrigger><SelectValue /></SelectTrigger>
                          <SelectContent>
                            {Object.entries(EQUIPMENT_STATUS_LABEL).map(([val, label]) => (
                              <SelectItem key={val} value={val}>{label}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <div>
                      <Label>비고</Label>
                      <div className="mt-1">
                        <Textarea value={formData.memo} onChange={(e) => handleFormChange('memo', e.target.value)} rows={4} placeholder="비고를 입력하세요" />
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 설비 사진 (수정 모드) */}
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base">설비 사진</CardTitle>
                    <div>
                      <input
                        ref={photoInputRef}
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handlePhotoUpload}
                      />
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => photoInputRef.current?.click()}
                        disabled={isUploading || equipment.photos.length >= 10}
                      >
                        {isUploading ? (
                          <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                        ) : (
                          <ImagePlus className="h-4 w-4 mr-1" />
                        )}
                        사진 추가
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  {equipment.photos.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground text-sm">
                      등록된 사진이 없습니다.
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {equipment.photos.map((photo) => (
                        <div key={photo.id} className="space-y-2">
                          <div className="relative border rounded-lg overflow-hidden bg-gray-50 group">
                            {/* eslint-disable-next-line @next/next/no-img-element */}
                            <img
                              src={`/api/proxy/files/${photo.id}/download`}
                              alt={photo.displayName}
                              className="w-full h-auto max-h-[400px] object-contain"
                            />
                            <Button
                              variant="destructive"
                              size="sm"
                              className="absolute top-2 right-2 h-7 px-2 opacity-0 group-hover:opacity-100 transition-opacity"
                              onClick={() => handlePhotoDelete(photo.id)}
                            >
                              <Trash2 className="h-3.5 w-3.5 mr-1" />
                              삭제
                            </Button>
                          </div>
                          <p className="text-xs text-muted-foreground">{photo.displayName}</p>
                        </div>
                      ))}
                    </div>
                  )}
                  {equipment.photos.length >= 10 && (
                    <p className="text-xs text-muted-foreground mt-2">최대 10장까지 등록 가능합니다.</p>
                  )}
                </CardContent>
              </Card>
            </>
          )}
        </TabsContent>

        {/* ==================== 점검항목 탭 ==================== */}
        <TabsContent value="inspection" className="space-y-4">
          <Card>
            <CardHeader className="space-y-3">
              <CardTitle className="text-base">점검항목 템플릿</CardTitle>
              <div className="flex flex-col gap-2 md:flex-row md:items-center">
                <Button variant="outline" size="sm" className="w-full md:w-auto" onClick={() => { setCopyTargetCycles([]); setShowCopyDialog(true); }}>
                  다른 주기에 복사
                </Button>
                <Button size="sm" className="w-full md:w-auto" onClick={() => { setNewTemplate({ inspectionCycle: selectedCycle, itemNo: '', checkPoint: '', checkItem: '', checkTiming: '', checkFrequency: '', checkMethod: '' }); setShowAddTemplate(true); }}>
                  <Plus className="h-4 w-4 mr-1" />
                  항목 추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {/* 주기 탭 버튼 */}
              <div className="grid grid-cols-2 gap-1 mt-3 mb-4 border-b pb-3 md:flex md:flex-wrap md:mt-0">
                {INSPECTION_CYCLES.map((cycle) => (
                  <Button
                    key={cycle}
                    variant={selectedCycle === cycle ? 'default' : 'ghost'}
                    size="sm"
                    className={selectedCycle === cycle ? '' : 'text-muted-foreground'}
                    onClick={() => setSelectedCycle(cycle)}
                  >
                    {INSPECTION_CYCLE_LABEL[cycle]}
                    {selectedCycle === cycle && templates.length > 0 && (
                      <Badge variant="secondary" className="ml-1.5 h-5 px-1.5 text-xs">
                        {templates.length}
                      </Badge>
                    )}
                  </Button>
                ))}
              </div>

              {/* 점검항목 목록 */}
              {isLoadingTemplates ? (
                <div className="flex justify-center py-8">
                  <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                </div>
              ) : templates.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground text-sm">
                  등록된 점검항목이 없습니다.
                </div>
              ) : (
                <>
                  {/* PC: 테이블 */}
                  <div className="hidden md:block">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[60px] text-center">번호</TableHead>
                          <TableHead>점검개소</TableHead>
                          <TableHead>점검항목</TableHead>
                          <TableHead className="w-[80px]">시기</TableHead>
                          <TableHead className="w-[80px]">주기</TableHead>
                          <TableHead>점검방법</TableHead>
                          <TableHead className="w-[60px] text-center">액션</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {templates.map((t, idx) => (
                          <TableRow key={t.id}>
                            <TableCell className="text-center">{t.itemNo || idx + 1}</TableCell>
                            <TableCell>{t.checkPoint}</TableCell>
                            <TableCell>{t.checkItem}</TableCell>
                            <TableCell>{t.checkTiming || '-'}</TableCell>
                            <TableCell>{t.checkFrequency || '-'}</TableCell>
                            <TableCell>{t.checkMethod || '-'}</TableCell>
                            <TableCell className="text-center">
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-red-600 hover:text-red-700"
                                onClick={() => handleDeleteTemplate(t.id)}
                              >
                                삭제
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                  {/* 모바일: 카드 리스트 */}
                  <div className="md:hidden space-y-3">
                    {templates.map((t, idx) => (
                      <div key={t.id} className="border rounded-lg p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-medium">{t.itemNo || idx + 1}. {t.checkPoint}</span>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 px-2 text-red-600 hover:text-red-700"
                            onClick={() => handleDeleteTemplate(t.id)}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                        <div className="space-y-1 text-sm">
                          <div><span className="text-muted-foreground">점검항목: </span>{t.checkItem}</div>
                          <div><span className="text-muted-foreground">시기: </span>{t.checkTiming || '-'}</div>
                          <div><span className="text-muted-foreground">주기: </span>{t.checkFrequency || '-'}</div>
                        </div>
                        {t.checkMethod && (
                          <p className="text-xs text-muted-foreground">{t.checkMethod}</p>
                        )}
                      </div>
                    ))}
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ==================== 수리이력 탭 ==================== */}
        <TabsContent value="repairs" className="space-y-4">
          <Card>
            <CardHeader><CardTitle className="text-base">수리이력</CardTitle></CardHeader>
            <CardContent>
              {isLoadingRepairs ? (
                <div className="flex justify-center py-8">
                  <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                </div>
              ) : repairs.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground text-sm">
                  수리이력이 없습니다.
                </div>
              ) : (
                <>
                  {/* PC: 테이블 */}
                  <div className="hidden md:block">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[60px] text-center">번호</TableHead>
                          <TableHead className="w-[110px]">수리일</TableHead>
                          <TableHead className="w-[70px]">보전구분</TableHead>
                          <TableHead>수리내용</TableHead>
                          <TableHead className="w-[80px] text-right">수리시간</TableHead>
                          <TableHead className="w-[100px] text-right">수리비용</TableHead>
                          <TableHead className="w-[100px]">외주업체</TableHead>
                          <TableHead className="w-[80px]">수리자</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {repairs.map((r, idx) => (
                          <TableRow key={r.id}>
                            <TableCell className="text-center">{idx + 1}</TableCell>
                            <TableCell>{r.repairDate}</TableCell>
                            <TableCell>
                              {r.repairType ? (
                                <Badge variant="secondary" className={r.repairType === 'internal' ? 'bg-yellow-100 text-yellow-700' : 'bg-blue-100 text-blue-700'}>
                                  {REPAIR_TYPE_LABEL[r.repairType]}
                                </Badge>
                              ) : '-'}
                            </TableCell>
                            <TableCell className="max-w-[300px] truncate">{r.description || '-'}</TableCell>
                            <TableCell className="text-right">{r.repairHours ? `${r.repairHours}h` : '-'}</TableCell>
                            <TableCell className="text-right">{r.cost ? Number(r.cost).toLocaleString() + '원' : '-'}</TableCell>
                            <TableCell>{r.vendor || '-'}</TableCell>
                            <TableCell>{r.repairerName || '-'}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                  {/* 모바일: 카드 리스트 */}
                  <div className="md:hidden space-y-3">
                    {repairs.map((r, idx) => (
                      <div key={r.id} className="border rounded-lg p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-medium">{r.repairDate}</span>
                          {r.repairType ? (
                            <Badge variant="secondary" className={r.repairType === 'internal' ? 'bg-yellow-100 text-yellow-700' : 'bg-blue-100 text-blue-700'}>
                              {REPAIR_TYPE_LABEL[r.repairType]}
                            </Badge>
                          ) : null}
                        </div>
                        <p className="text-sm">{r.description || '-'}</p>
                        <div className="grid grid-cols-2 gap-1 text-sm">
                          <div><span className="text-muted-foreground">수리시간: </span>{r.repairHours ? `${r.repairHours}h` : '-'}</div>
                          <div><span className="text-muted-foreground">수리비용: </span>{r.cost ? Number(r.cost).toLocaleString() + '원' : '-'}</div>
                          <div><span className="text-muted-foreground">외주업체: </span>{r.vendor || '-'}</div>
                          <div><span className="text-muted-foreground">수리자: </span>{r.repairerName || '-'}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* ==================== 하단 버튼 (sticky 하단 바) ==================== */}
      <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}>
        {mode === 'view' ? (
          <>
            <Button variant="outline" size="sm" className="md:size-default" onClick={() => router.push('/quality/equipment')}>
              <ArrowLeft className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">목록으로</span>
            </Button>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" className="md:size-default text-destructive hover:bg-destructive hover:text-destructive-foreground" onClick={() => setShowDelete(true)}>
                <Trash2 className="h-4 w-4 md:mr-2" />
                <span className="hidden md:inline">삭제</span>
              </Button>
              <Button size="sm" className="md:size-default" onClick={enterEditMode}>
                <Pencil className="h-4 w-4 md:mr-2" />
                <span className="hidden md:inline">수정</span>
              </Button>
            </div>
          </>
        ) : (
          <>
            <Button variant="outline" size="sm" className="md:size-default" onClick={cancelEdit}>
              <X className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">취소</span>
            </Button>
            <Button size="sm" className="md:size-default" onClick={handleSave} disabled={isSaving}>
              {isSaving ? <Loader2 className="h-4 w-4 md:mr-2 animate-spin" /> : <Save className="h-4 w-4 md:mr-2" />}
              <span className="hidden md:inline">저장</span>
            </Button>
          </>
        )}
      </div>

      {/* ==================== 모달들 ==================== */}

      {/* 삭제 확인 */}
      <DeleteConfirmDialog
        open={showDelete}
        onOpenChange={(open: boolean) => !open && setShowDelete(false)}
        itemName={equipment.name}
        description={`"${equipment.name}" 설비를 삭제하시겠습니까?`}
        loading={isDeleting}
        onConfirm={handleDelete}
      />

      {/* 점검항목 추가 모달 */}
      <Dialog open={showAddTemplate} onOpenChange={setShowAddTemplate}>
        <DialogContent className="sm:max-w-[480px]">
          <DialogHeader>
            <DialogTitle>점검항목 추가</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>점검주기 <span className="text-red-500">*</span></Label>
                <div className="mt-1">
                  <Select value={selectedCycle} disabled>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {INSPECTION_CYCLES.map((c) => (
                        <SelectItem key={c} value={c}>{INSPECTION_CYCLE_LABEL[c]}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <FormField
                label="항목번호"
                value={newTemplate.itemNo}
                onChange={(v) => setNewTemplate((p) => ({ ...p, itemNo: v }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <FormField
                label="점검개소"
                required
                value={newTemplate.checkPoint}
                onChange={(v) => setNewTemplate((p) => ({ ...p, checkPoint: v }))}
                placeholder="겉모양"
              />
              <FormField
                label="점검항목"
                required
                value={newTemplate.checkItem}
                onChange={(v) => setNewTemplate((p) => ({ ...p, checkItem: v }))}
                placeholder="청결상태"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>시기</Label>
                <div className="mt-1">
                  <Select
                    value={newTemplate.checkTiming || '_none'}
                    onValueChange={(v) => setNewTemplate((p) => ({ ...p, checkTiming: v === '_none' ? '' : v }))}
                  >
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="_none">선택</SelectItem>
                      <SelectItem value="정지 시">정지 시</SelectItem>
                      <SelectItem value="가동 중">가동 중</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <FormField
                label="주기"
                value={newTemplate.checkFrequency}
                onChange={(v) => setNewTemplate((p) => ({ ...p, checkFrequency: v }))}
                placeholder="1회/일"
              />
            </div>
            <div>
              <Label>점검방법</Label>
              <div className="mt-1">
                <Textarea
                  value={newTemplate.checkMethod}
                  onChange={(e) => setNewTemplate((p) => ({ ...p, checkMethod: e.target.value }))}
                  placeholder="육안 확인"
                  rows={2}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowAddTemplate(false)}>취소</Button>
            <Button onClick={handleAddTemplate}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 점검항목 복사 모달 */}
      <Dialog open={showCopyDialog} onOpenChange={setShowCopyDialog}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>점검항목 복사</DialogTitle>
          </DialogHeader>
          <div className="py-2">
            <p className="text-sm text-muted-foreground mb-4">
              <span className="font-medium text-primary">{INSPECTION_CYCLE_LABEL[selectedCycle]}</span> 점검항목을 선택한 주기에 복사합니다.
            </p>
            <div className="space-y-3">
              {INSPECTION_CYCLES.filter((c) => c !== selectedCycle).map((cycle) => (
                <label key={cycle} className="flex items-center gap-2 cursor-pointer">
                  <Checkbox
                    checked={copyTargetCycles.includes(cycle)}
                    onCheckedChange={(checked) => {
                      setCopyTargetCycles((prev) =>
                        checked
                          ? [...prev, cycle]
                          : prev.filter((c) => c !== cycle)
                      );
                    }}
                  />
                  <span className="text-sm">{INSPECTION_CYCLE_LABEL[cycle]}</span>
                </label>
              ))}
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCopyDialog(false)}>취소</Button>
            <Button onClick={handleCopyTemplates} disabled={copyTargetCycles.length === 0}>복사</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
