'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Package, Folder, Search, Info, Loader2 } from 'lucide-react';
import { ContentSkeleton } from '@/components/ui/skeleton';
import type { ItemSection } from '@/contexts/ItemMasterContext';
import type { SectionUsageResponse } from '@/types/item-master-api';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

interface ImportSectionDialogProps {
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
  independentSections: ItemSection[];
  selectedSectionId: number | null;
  setSelectedSectionId: (id: number | null) => void;
  onImport: () => void;
  onRefresh: () => Promise<void>;
  onGetUsage?: (sectionId: number) => Promise<SectionUsageResponse>;
  isLoading?: boolean;
}

export function ImportSectionDialog({
  isOpen,
  setIsOpen,
  independentSections,
  selectedSectionId,
  setSelectedSectionId,
  onImport,
  onRefresh,
  onGetUsage,
  isLoading = false,
}: ImportSectionDialogProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [usageInfo, setUsageInfo] = useState<SectionUsageResponse | null>(null);
  const [isLoadingUsage, setIsLoadingUsage] = useState(false);

  // Filter sections by search query
  const filteredSections = independentSections.filter(section =>
    section.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    section.description?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Load sections when dialog opens
  useEffect(() => {
    if (isOpen) {
      onRefresh();
      setSearchQuery('');
      setUsageInfo(null);
    }
  }, [isOpen]);

  // Load usage info when section is selected
  useEffect(() => {
    const loadUsage = async () => {
      if (selectedSectionId && onGetUsage) {
        setIsLoadingUsage(true);
        try {
          const usage = await onGetUsage(selectedSectionId);
          setUsageInfo(usage);
        } catch (error) {
          if (isNextRedirectError(error)) throw error;
          console.error('Failed to load usage info:', error);
          setUsageInfo(null);
        } finally {
          setIsLoadingUsage(false);
        }
      } else {
        setUsageInfo(null);
      }
    };
    loadUsage();
  }, [selectedSectionId, onGetUsage]);

  const handleClose = () => {
    setIsOpen(false);
    setSelectedSectionId(null);
    setSearchQuery('');
    setUsageInfo(null);
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => {
      if (!open) handleClose();
      else setIsOpen(open);
    }}>
      <DialogContent className="max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>섹션 불러오기</DialogTitle>
          <DialogDescription>
            독립 섹션을 선택하여 현재 페이지에 연결합니다. 섹션 데이터는 공유됩니다.
          </DialogDescription>
        </DialogHeader>

        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="섹션 검색..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        <div className="space-y-4">
          {isLoading ? (
            <ContentSkeleton type="list" rows={5} />
          ) : filteredSections.length === 0 ? (
            <div className="text-center py-8">
              <Folder className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">
                {searchQuery ? '검색 결과가 없습니다' : '사용 가능한 독립 섹션이 없습니다'}
              </p>
              <p className="text-sm text-muted-foreground mt-2">
                섹션 탭에서 새 섹션을 생성해주세요
              </p>
            </div>
          ) : (
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {filteredSections.map((section) => (
                <div
                  key={section.id}
                  onClick={() => setSelectedSectionId(section.id)}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    selectedSectionId === section.id
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                      : 'hover:bg-gray-50 dark:hover:bg-gray-800'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    <div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-900">
                      {section.section_type === 'BOM' ? (
                        <Package className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                      ) : (
                        <Folder className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1 flex-wrap">
                        <h4 className="font-medium">{section.title}</h4>
                        <Badge variant={section.section_type === 'BOM' ? 'default' : 'secondary'}>
                          {section.section_type}
                        </Badge>
                        {section.is_template && (
                          <Badge variant="outline" className="text-xs">템플릿</Badge>
                        )}
                      </div>
                      {section.description && (
                        <p className="text-sm text-muted-foreground mb-2 line-clamp-2">{section.description}</p>
                      )}
                      <div className="flex items-center gap-4 text-xs text-muted-foreground">
                        <span>{section.fields?.length || 0}개 필드</span>
                        {section.section_type === 'BOM' && (
                          <span>{section.bom_items?.length || 0}개 BOM 항목</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Usage Info Panel */}
          {selectedSectionId && (
            <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border">
              <div className="flex items-center gap-2 mb-2">
                <Info className="h-4 w-4 text-blue-500" />
                <Label className="font-medium">사용처 정보</Label>
              </div>
              {isLoadingUsage ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span>사용처를 확인하는 중...</span>
                </div>
              ) : usageInfo ? (
                <div className="text-sm space-y-1">
                  <p>총 {usageInfo.total_usage_count}개 페이지에서 사용 중</p>
                  {usageInfo.linked_pages.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {usageInfo.linked_pages.slice(0, 5).map(page => (
                        <Badge key={page.id} variant="outline" className="text-xs">
                          {page.page_name}
                        </Badge>
                      ))}
                      {usageInfo.linked_pages.length > 5 && (
                        <Badge variant="outline" className="text-xs">
                          +{usageInfo.linked_pages.length - 5}개 더
                        </Badge>
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">사용처 정보를 불러올 수 없습니다</p>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button
            onClick={() => {
              onImport();
              handleClose();
            }}
            disabled={!selectedSectionId || isLoading}
          >
            불러오기
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}