'use client';

/**
 * 설비 등록/수정 폼
 *
 * 섹션: 기본정보 / 제조사 정보 / 설치 정보 / 관리자·비고
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2, Save, X, ImagePlus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { useMenuStore } from '@/stores/menuStore';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FormField } from '@/components/molecules/FormField';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  createEquipment,
  updateEquipment,
  getEquipmentOptions,
  getEquipmentDetail,
  getManagerOptions,
  uploadEquipmentPhoto,
} from './actions';
import type {
  EquipmentFormData,
  EquipmentOptions,
  Equipment,
  ManagerOption,
} from './types';
import { EQUIPMENT_STATUS_LABEL } from './types';

const initialFormData: EquipmentFormData = {
  equipmentCode: '',
  name: '',
  equipmentType: '',
  specification: '',
  manufacturer: '',
  modelName: '',
  serialNo: '',
  location: '',
  productionLine: '',
  purchaseDate: '',
  installDate: '',
  purchasePrice: '',
  usefulLife: '',
  status: 'active',
  managerId: '',
  subManagerId: '',
  memo: '',
};

interface EquipmentFormProps {
  /** 수정 모드일 때 설비 ID */
  equipmentId?: string;
  /** 수정 모드일 때 기존 데이터 */
  initialData?: Equipment;
  /** 저장 후 콜백 */
  onSaveSuccess?: () => void;
}

export function EquipmentForm({ equipmentId, initialData, onSaveSuccess }: EquipmentFormProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const isEditMode = !!equipmentId;

  const [formData, setFormData] = useState<EquipmentFormData>(initialFormData);
  const [options, setOptions] = useState<EquipmentOptions | null>(null);
  const [managers, setManagers] = useState<ManagerOption[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoading, setIsLoading] = useState(!!equipmentId && !initialData);
  const [pendingPhotos, setPendingPhotos] = useState<File[]>([]);
  const [photoPreviews, setPhotoPreviews] = useState<string[]>([]);
  const photoInputRef = useRef<HTMLInputElement>(null);

  // 옵션 + 직원 목록 로드
  useEffect(() => {
    Promise.all([
      getEquipmentOptions(),
      getManagerOptions(),
    ]).then(([optResult, mgrResult]) => {
      if (optResult.success && optResult.data) {
        setOptions(optResult.data);
      }
      setManagers(mgrResult);
    });
  }, []);

  // 수정 모드: 기존 데이터 세팅
  useEffect(() => {
    if (initialData) {
      setFormData({
        equipmentCode: initialData.equipmentCode,
        name: initialData.name,
        equipmentType: initialData.equipmentType,
        specification: initialData.specification,
        manufacturer: initialData.manufacturer,
        modelName: initialData.modelName,
        serialNo: initialData.serialNo,
        location: initialData.location,
        productionLine: initialData.productionLine,
        purchaseDate: initialData.purchaseDate,
        installDate: initialData.installDate,
        purchasePrice: initialData.purchasePrice,
        usefulLife: initialData.usefulLife ? String(initialData.usefulLife) : '',
        status: initialData.status,
        managerId: initialData.managerId ? String(initialData.managerId) : '',
        subManagerId: initialData.subManagerId ? String(initialData.subManagerId) : '',
        memo: initialData.memo,
      });
    } else if (equipmentId) {
      setIsLoading(true);
      getEquipmentDetail(equipmentId).then((result) => {
        if (result.success && result.data) {
          const d = result.data;
          setFormData({
            equipmentCode: d.equipmentCode,
            name: d.name,
            equipmentType: d.equipmentType,
            specification: d.specification,
            manufacturer: d.manufacturer,
            modelName: d.modelName,
            serialNo: d.serialNo,
            location: d.location,
            productionLine: d.productionLine,
            purchaseDate: d.purchaseDate,
            installDate: d.installDate,
            purchasePrice: d.purchasePrice,
            usefulLife: d.usefulLife ? String(d.usefulLife) : '',
            status: d.status,
            managerId: d.managerId ? String(d.managerId) : '',
            subManagerId: d.subManagerId ? String(d.subManagerId) : '',
            memo: d.memo,
          });
        } else {
          toast.error(result.error || '설비 데이터를 불러올 수 없습니다.');
          router.push('/quality/equipment');
        }
        setIsLoading(false);
      });
    }
  }, [equipmentId, initialData, router]);

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

  const handlePhotoSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (pendingPhotos.length >= 10) {
      toast.error('최대 10장까지 등록 가능합니다.');
      return;
    }
    setPendingPhotos((prev) => [...prev, file]);
    setPhotoPreviews((prev) => [...prev, URL.createObjectURL(file)]);
    if (photoInputRef.current) photoInputRef.current.value = '';
  }, [pendingPhotos.length]);

  const handlePhotoRemove = useCallback((index: number) => {
    URL.revokeObjectURL(photoPreviews[index]);
    setPendingPhotos((prev) => prev.filter((_, i) => i !== index));
    setPhotoPreviews((prev) => prev.filter((_, i) => i !== index));
  }, [photoPreviews]);

  const handleSubmit = useCallback(async () => {
    if (!formData.equipmentCode.trim()) {
      toast.error('설비코드를 입력하세요.');
      return;
    }
    if (!formData.name.trim()) {
      toast.error('설비명을 입력하세요.');
      return;
    }

    setIsSubmitting(true);
    try {
      const result = isEditMode
        ? await updateEquipment(equipmentId!, formData)
        : await createEquipment(formData);

      if (result.success) {
        // 신규 등록 시 대기 중인 사진 업로드
        if (!isEditMode && pendingPhotos.length > 0 && result.data?.id) {
          const newId = String(result.data.id);
          let uploadedCount = 0;
          for (const file of pendingPhotos) {
            const photoResult = await uploadEquipmentPhoto(newId, file);
            if (photoResult.success) {
              uploadedCount++;
            } else {
              toast.error(photoResult.error || '사진 업로드에 실패했습니다.');
            }
          }
          if (uploadedCount > 0) {
            toast.success(`사진 ${uploadedCount}장이 업로드되었습니다.`);
          }
          // preview URL 정리
          photoPreviews.forEach((url) => URL.revokeObjectURL(url));
        }
        toast.success(isEditMode ? '설비가 수정되었습니다.' : '설비가 등록되었습니다.');
        if (onSaveSuccess) {
          onSaveSuccess();
        } else {
          router.push('/quality/equipment');
        }
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, isEditMode, equipmentId, onSaveSuccess, router, pendingPhotos, photoPreviews]);

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

  return (
    <div className="space-y-6 p-3 md:p-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">{isEditMode ? '설비 수정' : '설비 등록'}</h1>
        <Button
          variant="link"
          className="text-muted-foreground"
          onClick={() => router.push('/quality/equipment')}
        >
          ← 목록으로
        </Button>
      </div>

      {/* 기본정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">기본정보</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <FormField
                label="설비코드"
                required
                value={formData.equipmentCode}
                onChange={(v) => handleChange('equipmentCode', v)}
                placeholder="KD-M-001"
              />
              <p className="text-xs text-muted-foreground mt-1">예: KD-M-001, KD-S-002</p>
            </div>
            <FormField
              label="설비명"
              required
              value={formData.name}
              onChange={(v) => handleChange('name', v)}
              placeholder="포밍기#1"
            />
            <div>
              <Label>설비유형</Label>
              <div className="mt-1">
                <Select
                  value={formData.equipmentType || '_none'}
                  onValueChange={(v) => handleChange('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) => handleChange('specification', v)}
              placeholder="규격"
            />
          </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) => handleChange('manufacturer', v)}
              placeholder="제조사"
            />
            <FormField
              label="모델명"
              value={formData.modelName}
              onChange={(v) => handleChange('modelName', v)}
              placeholder="모델명"
            />
            <FormField
              label="제조번호"
              value={formData.serialNo}
              onChange={(v) => handleChange('serialNo', v)}
              placeholder="제조번호"
            />
          </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) => handleChange('location', v)}
              placeholder="1공장-1F"
            />
            <div>
              <Label>생산라인</Label>
              <div className="mt-1">
                <Select
                  value={formData.productionLine || '_none'}
                  onValueChange={(v) => handleChange('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) => handleChange('purchaseDate', v)}
            />
            <FormField
              label="설치일"
              type="date"
              value={formData.installDate}
              onChange={(v) => handleChange('installDate', v)}
            />
            <FormField
              label="구입가격 (원)"
              type="number"
              value={formData.purchasePrice}
              onChange={(v) => handleChange('purchasePrice', v)}
              placeholder="구입가격"
            />
            <FormField
              label="내용연수 (년)"
              type="number"
              value={formData.usefulLife}
              onChange={(v) => handleChange('usefulLife', v)}
              placeholder="내용연수"
            />
          </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) => handleChange('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) => handleChange('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 className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>상태</Label>
                <div className="mt-1">
                  <Select
                    value={formData.status}
                    onValueChange={(v) => handleChange('status', v)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="상태 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {Object.entries(EQUIPMENT_STATUS_LABEL).map(([val, label]) => (
                        <SelectItem key={val} value={val}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
            <div>
              <Label>비고</Label>
              <div className="mt-1">
                <Textarea
                  value={formData.memo}
                  onChange={(e) => handleChange('memo', e.target.value)}
                  placeholder="비고를 입력하세요"
                  rows={4}
                />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 설비 사진 */}
      {!isEditMode && (
        <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={handlePhotoSelect}
                />
                <Button
                  variant="outline"
                  size="sm"
                  type="button"
                  onClick={() => photoInputRef.current?.click()}
                  disabled={pendingPhotos.length >= 10}
                >
                  <ImagePlus className="h-4 w-4 mr-1" />
                  사진 추가
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            {pendingPhotos.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">
                {pendingPhotos.map((file, index) => (
                  <div key={`photo-${index}`} 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={photoPreviews[index]}
                        alt={file.name}
                        className="w-full h-auto max-h-[400px] object-contain"
                      />
                      <Button
                        variant="destructive"
                        size="sm"
                        type="button"
                        className="absolute top-2 right-2 h-7 px-2 opacity-0 group-hover:opacity-100 transition-opacity"
                        onClick={() => handlePhotoRemove(index)}
                      >
                        <Trash2 className="h-3.5 w-3.5 mr-1" />
                        삭제
                      </Button>
                    </div>
                    <p className="text-xs text-muted-foreground">{file.name}</p>
                  </div>
                ))}
              </div>
            )}
            {pendingPhotos.length >= 10 && (
              <p className="text-xs text-muted-foreground mt-2">최대 10장까지 등록 가능합니다.</p>
            )}
          </CardContent>
        </Card>
      )}

      {/* 하단 버튼 (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`}>
        <Button variant="outline" onClick={() => router.push('/quality/equipment')}>
          <X className="h-4 w-4 mr-1" />
          취소
        </Button>
        <Button onClick={handleSubmit} disabled={isSubmitting}>
          {isSubmitting ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <Save className="h-4 w-4 mr-1" />}
          저장
        </Button>
      </div>
    </div>
  );
}
