'use client';

/**
 * 현장관리 상세 페이지
 * IntegratedDetailTemplate 마이그레이션 완료 (2026-01-20)
 */

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Mic } from 'lucide-react';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { FileList, type NewFile, type ExistingFile } from '@/components/ui/file-list';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { siteConfig } from './siteConfig';
import { toast } from 'sonner';
import { useDaumPostcode } from '@/hooks/useDaumPostcode';
import type { Site } from './types';
import { SITE_STATUS_OPTIONS } from './types';

// 도면 파일 타입
interface DrawingDocument {
  id: string;
  fileName: string;
  fileUrl: string;
  fileSize: number;
  uploadedAt: string;
}

interface SiteDetailFormProps {
  site?: Site;
  mode?: 'view' | 'edit';
}

export default function SiteDetailForm({ site, mode = 'view' }: SiteDetailFormProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';

  // 새 파일 상태
  const [newFiles, setNewFiles] = useState<File[]>([]);

  // 목데이터: 기존 도면 파일
  const MOCK_DRAWINGS: DrawingDocument[] = site ? [
    {
      id: '1',
      fileName: '현장배치도_v2.pdf',
      fileUrl: '#',
      fileSize: 2458624, // 2.4MB
      uploadedAt: '2024-12-15T10:30:00',
    },
    {
      id: '2',
      fileName: '구조도면_최종.dwg',
      fileUrl: '#',
      fileSize: 5242880, // 5MB
      uploadedAt: '2024-12-16T14:20:00',
    },
    {
      id: '3',
      fileName: '현장사진_001.jpg',
      fileUrl: '#',
      fileSize: 1048576, // 1MB
      uploadedAt: '2024-12-18T09:15:00',
    },
  ] : [];

  // 도면 파일 목록
  const [drawings, setDrawings] = useState<DrawingDocument[]>(MOCK_DRAWINGS);

  // 폼 상태
  const [formData, setFormData] = useState({
    siteCode: site?.siteCode || '',
    partnerName: site?.partnerName || '',
    siteName: site?.siteName || '',
    status: site?.status || 'active',
    zonecode: '',
    address: site?.address || '',
    addressDetail: '',
    longitude: '',
    latitude: '',
    memo: '',
  });

  const [isSubmitting, setIsSubmitting] = useState(false);

  // Daum 우편번호 검색
  const { openPostcode, isScriptLoaded } = useDaumPostcode({
    onComplete: (result) => {
      setFormData((prev) => ({
        ...prev,
        zonecode: result.zonecode,
        address: result.address,
      }));
    },
  });

  // 입력 핸들러
  const handleInputChange = useCallback(
    (field: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      setFormData((prev) => ({ ...prev, [field]: e.target.value }));
    },
    []
  );

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

  // 파일 추가 핸들러
  const handleFilesSelect = useCallback((files: File[]) => {
    setNewFiles((prev) => [...prev, ...files]);
  }, []);

  // 새 파일 삭제 핸들러
  const handleNewFileRemove = useCallback((index: number) => {
    setNewFiles((prev) => prev.filter((_, i) => i !== index));
  }, []);

  // 기존 파일 삭제 핸들러
  const handleExistingFileRemove = useCallback((docId: string | number) => {
    setDrawings((prev) => prev.filter((d) => d.id !== String(docId)));
  }, []);

  // 동적 config (mode에 따라 title 변경)
  const dynamicConfig = useMemo(() => {
    const titleMap: Record<string, string> = {
      edit: '현장 수정',
      view: '현장 상세',
    };
    return {
      ...siteConfig,
      title: titleMap[mode] || siteConfig.title,
    };
  }, [mode]);

  // onSubmit 핸들러 (Promise 반환)
  const handleFormSubmit = useCallback(async () => {
    if (!formData.siteName.trim()) {
      toast.error('현장명을 입력해주세요.');
      return { success: false, error: '현장명을 입력해주세요.' };
    }

    setIsSubmitting(true);
    try {
      // TODO: API 연동
      await new Promise((resolve) => setTimeout(resolve, 1000));
      toast.success('저장되었습니다.');
      router.push('/ko/construction/order/site-management');
      return { success: true };
    } catch {
      toast.error('저장에 실패했습니다.');
      return { success: false, error: '저장에 실패했습니다.' };
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, router]);

  // 폼 콘텐츠 렌더링
  const renderFormContent = useCallback(() => (
    <div className="space-y-6">
      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">기본 정보 *</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 현장번호 */}
            <div className="space-y-2">
              <Label htmlFor="siteCode">현장번호</Label>
              <Input
                id="siteCode"
                value={formData.siteCode}
                onChange={handleInputChange('siteCode')}
                placeholder="123-12-12345"
                disabled={isViewMode}
              />
            </div>

            {/* 거래처 */}
            <div className="space-y-2">
              <Label htmlFor="partnerName">거래처</Label>
              <Input
                id="partnerName"
                value={formData.partnerName}
                onChange={handleInputChange('partnerName')}
                placeholder="거래처명"
                disabled={isViewMode}
              />
            </div>

            {/* 현장명 */}
            <div className="space-y-2">
              <Label htmlFor="siteName">현장명</Label>
              <Input
                id="siteName"
                value={formData.siteName}
                onChange={handleInputChange('siteName')}
                placeholder="현장명"
                disabled={isViewMode}
              />
            </div>

            {/* 상태 */}
            <div className="space-y-2">
              <Label htmlFor="status">상태</Label>
              <Select
                value={formData.status}
                onValueChange={handleSelectChange('status')}
                disabled={isViewMode}
              >
                <SelectTrigger>
                  <SelectValue placeholder="상태 선택" />
                </SelectTrigger>
                <SelectContent>
                  {SITE_STATUS_OPTIONS.filter((opt) => opt.value !== 'all').map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 위치 정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">위치 정보 *</CardTitle>
          <p className="text-sm text-muted-foreground">
            주소 또는 경위도 값을 입력하세요
          </p>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 주소 */}
          <div className="space-y-2">
            <Label>주소</Label>
            <div className="flex gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={openPostcode}
                disabled={!isScriptLoaded || isViewMode}
                className="shrink-0"
              >
                우편번호 찾기
              </Button>
              <Input
                value={formData.address}
                onChange={handleInputChange('address')}
                placeholder="상세주소를 입력해주세요"
                disabled={isViewMode}
                className="flex-1"
              />
            </div>
          </div>

          {/* 경도/위도 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="longitude">경도</Label>
              <Input
                id="longitude"
                value={formData.longitude}
                onChange={handleInputChange('longitude')}
                placeholder="경도를 입력해주세요"
                disabled={isViewMode}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="latitude">위도</Label>
              <Input
                id="latitude"
                value={formData.latitude}
                onChange={handleInputChange('latitude')}
                placeholder="위도를 입력해주세요"
                disabled={isViewMode}
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 도면 정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">도면 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {!isViewMode && (
            <FileDropzone
              onFilesSelect={handleFilesSelect}
              multiple
              maxSize={10}
              title="클릭하여 파일을 찾거나, 마우스로 파일을 끌어오세요."
            />
          )}
          <FileList
            files={newFiles.map((file): NewFile => ({ file }))}
            existingFiles={drawings.map((doc): ExistingFile => ({
              id: doc.id,
              name: doc.fileName,
              size: doc.fileSize,
              url: doc.fileUrl,
            }))}
            onRemove={handleNewFileRemove}
            onRemoveExisting={handleExistingFileRemove}
            showRemove={!isViewMode}
            emptyMessage="업로드된 파일이 없습니다"
          />
        </CardContent>
      </Card>

      {/* 실측 정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">실측 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="memo">메모</Label>
            <div className="relative">
              <Textarea
                id="memo"
                value={formData.memo}
                onChange={handleInputChange('memo')}
                placeholder="메모를 입력하세요"
                disabled={isViewMode}
                className="min-h-[120px]"
              />
              {!isViewMode && (
                <Button
                  type="button"
                  variant="default"
                  size="sm"
                  className="absolute bottom-2 right-2"
                >
                  <Mic className="h-4 w-4 mr-1" />
                  녹음
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  ), [
    formData,
    isViewMode,
    drawings,
    newFiles,
    isScriptLoaded,
    handleInputChange,
    handleSelectChange,
    openPostcode,
    handleFilesSelect,
    handleNewFileRemove,
    handleExistingFileRemove,
  ]);

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode={isViewMode ? 'view' : 'edit'}
      initialData={formData}
      itemId={site?.id}
      isLoading={isSubmitting}
      onSubmit={handleFormSubmit}
      renderView={() => renderFormContent()}
      renderForm={() => renderFormContent()}
    />
  );
}