'use client';

/**
 * 항목 등록/수정 폼 컴포넌트
 *
 * 기획서 스크린샷 3 기준:
 * - 기본 정보: 항목 번호(자동), 항목명, 소개, 상태
 * - 문서 정보: 순서, 문서 번호, 문서, 개정, 시행일 + 행 추가/삭제
 */

import { useState, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Trash2, GripVertical } from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { toast } from 'sonner';
import type { ChecklistItem, ChecklistDocumentFormData } from '@/types/checklist';
import { createChecklistItem, updateChecklistItem } from './actions';
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';

const itemCreateConfig: DetailConfig = {
  title: '항목',
  description: '새로운 항목을 등록합니다',
  basePath: '',
  fields: [],
  actions: {
    showBack: true,
    showEdit: false,
    showDelete: false,
    showSave: true,
    submitLabel: '등록',
  },
};

const itemEditConfig: DetailConfig = {
  ...itemCreateConfig,
  description: '항목 정보를 수정합니다',
  actions: {
    ...itemCreateConfig.actions,
    submitLabel: '저장',
  },
};

interface ItemFormProps {
  mode: 'create' | 'edit';
  checklistId: string;
  initialData?: ChecklistItem;
}

export function ItemForm({ mode, checklistId, initialData }: ItemFormProps) {
  const router = useRouter();
  const isEdit = mode === 'edit';

  const [itemName, setItemName] = useState(initialData?.itemName || '');
  const [description, setDescription] = useState(initialData?.description || '');
  const [status, setStatus] = useState<string>(initialData?.status || '사용');

  // 문서 목록 상태
  const [documents, setDocuments] = useState<ChecklistDocumentFormData[]>(() => {
    if (initialData?.documents && initialData.documents.length > 0) {
      return initialData.documents.map((doc) => ({
        id: doc.id,
        documentCode: doc.documentCode,
        documentName: doc.documentName,
        revision: doc.revision,
        effectiveDate: doc.effectiveDate,
        order: doc.order,
      }));
    }
    return [];
  });

  // 문서 드래그&드롭 상태
  const [docDragIndex, setDocDragIndex] = useState<number | null>(null);
  const [docDragOverIndex, setDocDragOverIndex] = useState<number | null>(null);
  const docDragNodeRef = useRef<HTMLTableRowElement | null>(null);

  const handleDocDragStart = useCallback(
    (e: React.DragEvent<HTMLTableRowElement>, index: number) => {
      setDocDragIndex(index);
      docDragNodeRef.current = e.currentTarget;
      e.dataTransfer.effectAllowed = 'move';
      requestAnimationFrame(() => {
        if (docDragNodeRef.current) docDragNodeRef.current.style.opacity = '0.4';
      });
    },
    []
  );

  const handleDocDragOver = useCallback(
    (e: React.DragEvent<HTMLTableRowElement>, index: number) => {
      e.preventDefault();
      e.dataTransfer.dropEffect = 'move';
      setDocDragOverIndex(index);
    },
    []
  );

  const handleDocDragEnd = useCallback(() => {
    if (docDragNodeRef.current) docDragNodeRef.current.style.opacity = '1';
    setDocDragIndex(null);
    setDocDragOverIndex(null);
    docDragNodeRef.current = null;
  }, []);

  const handleDocDrop = useCallback(
    (e: React.DragEvent<HTMLTableRowElement>, dropIndex: number) => {
      e.preventDefault();
      if (docDragIndex === null || docDragIndex === dropIndex) return;

      setDocuments((prev) => {
        const updated = [...prev];
        const [moved] = updated.splice(docDragIndex, 1);
        updated.splice(dropIndex, 0, moved);
        return updated.map((doc, i) => ({ ...doc, order: i + 1 }));
      });

      handleDocDragEnd();
    },
    [docDragIndex, handleDocDragEnd]
  );

  const handleMoveDocument = useCallback((fromIndex: number, toIndex: number) => {
    setDocuments((prev) => {
      const updated = [...prev];
      const [moved] = updated.splice(fromIndex, 1);
      updated.splice(toIndex, 0, moved);
      return updated.map((doc, i) => ({ ...doc, order: i + 1 }));
    });
  }, []);

  const handleAddDocument = () => {
    setDocuments((prev) => [
      ...prev,
      {
        documentCode: '',
        documentName: '',
        revision: '',
        effectiveDate: '',
        order: prev.length + 1,
      },
    ]);
  };

  const handleRemoveDocument = (index: number) => {
    setDocuments((prev) => {
      const updated = prev.filter((_, i) => i !== index);
      return updated.map((doc, i) => ({ ...doc, order: i + 1 }));
    });
  };

  const handleDocumentChange = (
    index: number,
    field: keyof ChecklistDocumentFormData,
    value: string | number
  ) => {
    setDocuments((prev) =>
      prev.map((doc, i) => (i === index ? { ...doc, [field]: value } : doc))
    );
  };

  const handleSubmit = async (): Promise<{ success: boolean; error?: string }> => {
    if (!itemName.trim()) {
      toast.error('항목명을 입력해주세요.');
      return { success: false, error: '항목명을 입력해주세요.' };
    }

    const formData = {
      itemName: itemName.trim(),
      description: description.trim(),
      status: status as '사용' | '미사용',
      documents,
    };

    try {
      if (isEdit && initialData?.id) {
        const result = await updateChecklistItem(checklistId, initialData.id, formData);
        if (result.success) {
          toast.success('항목이 수정되었습니다.');
          router.push(
            `/ko/master-data/checklist-management/${checklistId}/items/${initialData.id}?mode=view`
          );
          return { success: true };
        } else {
          toast.error(result.error || '수정에 실패했습니다.');
          return { success: false, error: result.error };
        }
      } else {
        const result = await createChecklistItem(checklistId, formData);
        if (result.success && result.data) {
          toast.success('항목이 등록되었습니다.');
          router.push(`/ko/master-data/checklist-management/${checklistId}?mode=view`);
          return { success: true };
        } else {
          toast.error(result.error || '등록에 실패했습니다.');
          return { success: false, error: result.error };
        }
      }
    } catch {
      toast.error('처리 중 오류가 발생했습니다.');
      return { success: false, error: '처리 중 오류가 발생했습니다.' };
    }
  };

  const handleCancel = () => {
    if (isEdit && initialData?.id) {
      router.push(
        `/ko/master-data/checklist-management/${checklistId}/items/${initialData.id}?mode=view`
      );
    } else {
      router.push(`/ko/master-data/checklist-management/${checklistId}?mode=view`);
    }
  };

  const renderFormContent = useCallback(
    () => (
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="space-y-2">
                <Label>항목 번호</Label>
                <Input
                  value={initialData?.itemCode || '자동생성'}
                  disabled
                  className="bg-muted"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="itemName">항목명 *</Label>
                <Input
                  id="itemName"
                  value={itemName}
                  onChange={(e) => setItemName(e.target.value)}
                  placeholder="항목명을 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="description">소개</Label>
                <Input
                  id="description"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="소개를 입력하세요"
                />
              </div>
              <div className="space-y-2">
                <Label>상태</Label>
                <Select value={status} onValueChange={setStatus}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="사용">사용</SelectItem>
                    <SelectItem value="미사용">미사용</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 문서 정보 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">문서 정보</CardTitle>
            <div className="flex items-center justify-between mt-1">
              <span className="text-sm text-muted-foreground">
                총 {documents.length}건
              </span>
              <Button size="sm" type="button" onClick={handleAddDocument} className="ml-auto">
                <Plus className="h-4 w-4 mr-1" />
                문서 추가
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {documents.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                등록된 문서가 없습니다. [문서 추가] 버튼으로 추가해주세요.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full" style={{ minWidth: 700 }}>
                  <thead>
                    <tr className="border-b bg-muted/30">
                      <th className="w-16 min-w-[64px] px-2 py-3 text-center text-xs font-medium text-muted-foreground" />
                      <th className="w-14 min-w-[48px] px-2 py-3 text-center text-xs font-medium text-muted-foreground">
                        순서
                      </th>
                      <th className="min-w-[120px] px-2 py-3 text-left text-xs font-medium text-muted-foreground">
                        문서 번호
                      </th>
                      <th className="min-w-[120px] px-2 py-3 text-left text-xs font-medium text-muted-foreground">
                        문서
                      </th>
                      <th className="min-w-[70px] px-2 py-3 text-left text-xs font-medium text-muted-foreground">
                        개정
                      </th>
                      <th className="min-w-[140px] px-2 py-3 text-left text-xs font-medium text-muted-foreground">
                        시행일
                      </th>
                      <th className="w-14 min-w-[48px] px-2 py-3 text-center text-xs font-medium text-muted-foreground">
                        삭제
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {documents.map((doc, index) => (
                      <tr
                        key={`doc-${index}`}
                        draggable
                        onDragStart={(e) => handleDocDragStart(e, index)}
                        onDragOver={(e) => handleDocDragOver(e, index)}
                        onDragEnd={handleDocDragEnd}
                        onDrop={(e) => handleDocDrop(e, index)}
                        className={`border-b transition-colors ${
                          docDragOverIndex === index && docDragIndex !== index
                            ? 'border-t-2 border-t-primary'
                            : ''
                        }`}
                      >
                        <td className="w-16 px-2 py-2 text-center">
                          <div className="flex items-center justify-center gap-0.5">
                            <GripVertical className="h-4 w-4 text-muted-foreground cursor-grab active:cursor-grabbing" />
                            <ReorderButtons
                              onMoveUp={() => handleMoveDocument(index, index - 1)}
                              onMoveDown={() => handleMoveDocument(index, index + 1)}
                              isFirst={index === 0}
                              isLast={index === documents.length - 1}
                              size="xs"
                            />
                          </div>
                        </td>
                        <td className="w-14 px-2 py-2 text-center text-sm">
                          {doc.order}
                        </td>
                        <td className="px-2 py-2">
                          <Input
                            value={doc.documentCode}
                            onChange={(e) =>
                              handleDocumentChange(index, 'documentCode', e.target.value)
                            }
                            placeholder="문서 번호"
                            className="h-8"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <Input
                            value={doc.documentName}
                            onChange={(e) =>
                              handleDocumentChange(index, 'documentName', e.target.value)
                            }
                            placeholder="문서명"
                            className="h-8"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <Input
                            value={doc.revision}
                            onChange={(e) =>
                              handleDocumentChange(index, 'revision', e.target.value)
                            }
                            placeholder="REV"
                            className="h-8"
                          />
                        </td>
                        <td className="px-2 py-2">
                          <DatePicker
                            value={doc.effectiveDate}
                            onChange={(date) =>
                              handleDocumentChange(index, 'effectiveDate', date)
                            }
                            size="sm"
                          />
                        </td>
                        <td className="w-14 px-2 py-2 text-center">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                            onClick={() => handleRemoveDocument(index)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    ),
    [itemName, description, status, documents, initialData?.itemCode, docDragIndex, docDragOverIndex, handleDocDragStart, handleDocDragOver, handleDocDragEnd, handleDocDrop, handleMoveDocument]
  );

  const config = isEdit ? itemEditConfig : itemCreateConfig;

  return (
    <IntegratedDetailTemplate
      config={config}
      mode={isEdit ? 'edit' : 'create'}
      isLoading={false}
      onCancel={handleCancel}
      onSubmit={handleSubmit}
      renderForm={renderFormContent}
    />
  );
}
