'use client';

/**
 * 점검표 상세 뷰 컴포넌트
 *
 * 기획서 스크린샷 2 기준:
 * - 기본 정보: 점검표 번호, 점검표명, 상태
 * - 항목 목록 테이블: 드래그&드롭 순서변경 + 항목 등록 버튼
 * - 하단: 삭제, 수정 버튼
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Edit, GripVertical, Plus, Trash2 } from 'lucide-react';
import { ReorderButtons } from '@/components/molecules';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { useMenuStore } from '@/stores/menuStore';
import { usePermission } from '@/hooks/usePermission';
import { toast } from 'sonner';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { getChecklistItems, reorderChecklistItems, deleteChecklist } from './actions';
import type { Checklist, ChecklistItem } from '@/types/checklist';

interface ChecklistDetailProps {
  checklist: Checklist;
}

export function ChecklistDetail({ checklist }: ChecklistDetailProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const { canUpdate } = usePermission();

  const [items, setItems] = useState<ChecklistItem[]>([]);
  const [isItemsLoading, setIsItemsLoading] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // 드래그 상태
  const [dragIndex, setDragIndex] = useState<number | null>(null);
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
  const dragNodeRef = useRef<HTMLTableRowElement | null>(null);

  // 항목 목록 로드
  useEffect(() => {
    const loadItems = async () => {
      setIsItemsLoading(true);
      const result = await getChecklistItems(checklist.id);
      if (result.success && result.data) {
        setItems(result.data);
      }
      setIsItemsLoading(false);
    };
    loadItems();
  }, [checklist.id]);

  // 네비게이션
  const handleEdit = () => {
    router.push(`/ko/master-data/checklist-management/${checklist.id}?mode=edit`);
  };

  const handleList = () => {
    router.push('/ko/master-data/checklist-management');
  };

  const handleAddItem = () => {
    router.push(`/ko/master-data/checklist-management/${checklist.id}/items/new?mode=new`);
  };

  const handleItemClick = (itemId: string) => {
    router.push(`/ko/master-data/checklist-management/${checklist.id}/items/${itemId}?mode=view`);
  };

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      const result = await deleteChecklist(checklist.id);
      if (result.success) {
        toast.success('점검표가 삭제되었습니다.');
        router.push('/ko/master-data/checklist-management');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsDeleting(false);
      setDeleteDialogOpen(false);
    }
  };

  // ===== 드래그&드롭 =====
  const handleDragStart = useCallback(
    (e: React.DragEvent<HTMLTableRowElement>, index: number) => {
      setDragIndex(index);
      dragNodeRef.current = e.currentTarget;
      e.dataTransfer.effectAllowed = 'move';
      requestAnimationFrame(() => {
        if (dragNodeRef.current) dragNodeRef.current.style.opacity = '0.4';
      });
    },
    []
  );

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

  const handleDragEnd = useCallback(() => {
    if (dragNodeRef.current) dragNodeRef.current.style.opacity = '1';
    setDragIndex(null);
    setDragOverIndex(null);
    dragNodeRef.current = null;
  }, []);

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

      setItems((prev) => {
        const updated = [...prev];
        const [moved] = updated.splice(dragIndex, 1);
        updated.splice(dropIndex, 0, moved);
        const reordered = updated.map((item, i) => ({ ...item, order: i + 1 }));

        reorderChecklistItems(
          checklist.id,
          reordered.map((it) => ({ id: it.id, order: it.order }))
        );

        return reordered;
      });

      handleDragEnd();
    },
    [dragIndex, handleDragEnd, checklist.id]
  );

  // 화살표 버튼으로 순서 변경
  const handleMoveItem = useCallback((fromIndex: number, toIndex: number) => {
    setItems((prev) => {
      const updated = [...prev];
      const [moved] = updated.splice(fromIndex, 1);
      updated.splice(toIndex, 0, moved);
      const reordered = updated.map((item, i) => ({ ...item, order: i + 1 }));

      reorderChecklistItems(
        checklist.id,
        reordered.map((it) => ({ id: it.id, order: it.order }))
      );

      return reordered;
    });
  }, [checklist.id]);

  return (
    <PageLayout>
      <PageHeader title="점검표 상세" />

      <div className="space-y-6 pb-24">
        {/* 기본 정보 */}
        <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-3 gap-6">
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">점검표 번호</div>
                <div className="font-medium font-mono">{checklist.checklistCode}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">점검표</div>
                <div className="font-medium">{checklist.checklistName}</div>
              </div>
              <div className="space-y-1">
                <div className="text-sm text-muted-foreground">상태</div>
                <Badge variant={checklist.status === '사용' ? 'default' : 'secondary'}>
                  {checklist.status}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 항목 테이블 */}
        <Card>
          <CardHeader className="bg-muted/50">
            <CardTitle className="text-base">항목 목록</CardTitle>
            <div className="flex items-center justify-between mt-1">
              {!isItemsLoading && (
                <span className="text-sm text-muted-foreground">
                  총 {items.length}건
                </span>
              )}
              <Button size="sm" onClick={handleAddItem} className="ml-auto">
                <Plus className="h-4 w-4 mr-1" />
                항목 등록
              </Button>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {isItemsLoading ? (
              <div className="p-8 text-center text-muted-foreground">로딩 중...</div>
            ) : items.length === 0 ? (
              <div className="p-8 text-center text-muted-foreground">
                등록된 항목이 없습니다. [항목 등록] 버튼으로 추가해주세요.
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full" style={{ minWidth: 600 }}>
                  <thead>
                    <tr className="border-b bg-muted/30">
                      <th className="w-16 min-w-[64px] px-3 py-3 text-center text-xs font-medium text-muted-foreground" />
                      <th className="w-14 min-w-[48px] px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        No.
                      </th>
                      <th className="min-w-[100px] px-3 py-3 text-left text-xs font-medium text-muted-foreground">
                        항목 번호
                      </th>
                      <th className="w-16 min-w-[56px] px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        순서
                      </th>
                      <th className="min-w-[160px] px-3 py-3 text-left text-xs font-medium text-muted-foreground">
                        항목명
                      </th>
                      <th className="w-16 min-w-[48px] px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        문서
                      </th>
                      <th className="w-16 min-w-[56px] px-3 py-3 text-center text-xs font-medium text-muted-foreground">
                        사용
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {items.map((item, index) => (
                      <tr
                        key={item.id}
                        draggable
                        onDragStart={(e) => handleDragStart(e, index)}
                        onDragOver={(e) => handleDragOver(e, index)}
                        onDragEnd={handleDragEnd}
                        onDrop={(e) => handleDrop(e, index)}
                        onClick={() => handleItemClick(item.id)}
                        className={`border-b cursor-pointer transition-colors hover:bg-muted/50 ${
                          dragOverIndex === index && dragIndex !== index
                            ? 'border-t-2 border-t-primary'
                            : ''
                        }`}
                      >
                        <td
                          className="w-16 px-3 py-3 text-center"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <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={() => handleMoveItem(index, index - 1)}
                              onMoveDown={() => handleMoveItem(index, index + 1)}
                              isFirst={index === 0}
                              isLast={index === items.length - 1}
                              size="xs"
                            />
                          </div>
                        </td>
                        <td className="w-14 px-3 py-3 text-center text-sm text-muted-foreground">
                          {index + 1}
                        </td>
                        <td className="px-3 py-3 text-sm font-mono">{item.itemCode}</td>
                        <td className="w-16 px-3 py-3 text-center text-sm">
                          {item.order}
                        </td>
                        <td className="px-3 py-3 text-sm font-medium">{item.itemName}</td>
                        <td className="w-16 px-3 py-3 text-center text-sm">
                          {item.documentCount}
                        </td>
                        <td className="w-16 px-3 py-3 text-center">
                          <Badge
                            variant={item.status === '사용' ? 'default' : 'secondary'}
                            className="text-xs"
                          >
                            {item.status}
                          </Badge>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 하단 액션 버튼 (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={handleList} size="sm" className="md:size-default">
          <ArrowLeft className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">목록으로</span>
        </Button>
        {canUpdate && (
          <div className="flex items-center gap-2">
            <Button
              variant="destructive"
              onClick={() => setDeleteDialogOpen(true)}
              size="sm"
              className="md:size-default"
            >
              <Trash2 className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">삭제</span>
            </Button>
            <Button onClick={handleEdit} size="sm" className="md:size-default">
              <Edit className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수정</span>
            </Button>
          </div>
        )}
      </div>

      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        description="이 점검표를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
        loading={isDeleting}
        onConfirm={handleDelete}
      />
    </PageLayout>
  );
}
