import { useState } from 'react';
import { PageLayout } from './organisms/PageLayout';
import { PageHeader } from './organisms/PageHeader';
import { useData } from './contexts/DataContext';
import type { ItemPage, ItemSection, ItemField, ItemFieldProperty } from './contexts/DataContext';
import {
  Database,
  Plus,
  Edit,
  Trash2,
  ChevronRight,
  ChevronDown,
  FolderTree,
  FileText,
  Save,
  X,
  GripVertical,
  Settings,
  Eye,
  EyeOff
} from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import { Switch } from './ui/switch';
import { Badge } from './ui/badge';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from './ui/dialog';
import { toast } from 'sonner@2.0.3';
import img1 from 'figma:asset/ebb8bf609461642dd6bc2778c1d97da29c39ca30.png';
import img2 from 'figma:asset/1b39f1649e5a7c103e8b7fe5d2469a2fee92476e.png';

const ITEM_TYPE_OPTIONS = [
  { value: 'FG', label: '제품 (FG)' },
  { value: 'PT', label: '부품 (PT)' },
  { value: 'SM', label: '부자재 (SM)' },
  { value: 'RM', label: '원자재 (RM)' },
  { value: 'CS', label: '소모품 (CS)' }
];

const INPUT_TYPE_OPTIONS = [
  { value: 'textbox', label: '텍스트박스' },
  { value: 'dropdown', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'number', label: '숫자' },
  { value: 'date', label: '날짜' },
  { value: 'textarea', label: '텍스트영역' }
];

export function ItemMasterDataHierarchy() {
  const {
    itemPages,
    addItemPage,
    updateItemPage,
    deleteItemPage,
    addSectionToPage,
    updateSection,
    deleteSection,
    addFieldToSection,
    updateField,
    deleteField
  } = useData();

  const [selectedPage, setSelectedPage] = useState<ItemPage | null>(itemPages[0] || null);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});

  // 페이지 추가 다이얼로그
  const [isPageDialogOpen, setIsPageDialogOpen] = useState(false);
  const [newPageName, setNewPageName] = useState('');
  const [newPageItemType, setNewPageItemType] = useState<'FG' | 'PT' | 'SM' | 'RM' | 'CS'>('FG');

  // 섹션 추가 다이얼로그
  const [isSectionDialogOpen, setIsSectionDialogOpen] = useState(false);
  const [newSectionTitle, setNewSectionTitle] = useState('');
  const [newSectionDescription, setNewSectionDescription] = useState('');
  const [newSectionCategory, setNewSectionCategory] = useState('');

  // 항목 추가 다이얼로그
  const [isFieldDialogOpen, setIsFieldDialogOpen] = useState(false);
  const [selectedSectionForField, setSelectedSectionForField] = useState<string | null>(null);
  const [newFieldName, setNewFieldName] = useState('');
  const [newFieldKey, setNewFieldKey] = useState('');
  const [newFieldInputType, setNewFieldInputType] = useState<'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea'>('textbox');
  const [newFieldRequired, setNewFieldRequired] = useState(false);
  const [newFieldRow, setNewFieldRow] = useState(1);
  const [newFieldCol, setNewFieldCol] = useState(1);
  const [newFieldOptions, setNewFieldOptions] = useState('');
  const [newFieldCategory, setNewFieldCategory] = useState('');

  const toggleSection = (sectionId: string) => {
    setExpandedSections(prev => ({
      ...prev,
      [sectionId]: !prev[sectionId]
    }));
  };

  const handleAddPage = () => {
    if (!newPageName) {
      toast.error('페이지명을 입력해주세요');
      return;
    }

    const newPage: ItemPage = {
      id: `PAGE-${Date.now()}`,
      pageName: newPageName,
      itemType: newPageItemType,
      sections: [],
      isActive: true,
      createdAt: new Date().toISOString().split('T')[0]
    };

    addItemPage(newPage);
    setSelectedPage(newPage);
    setNewPageName('');
    setIsPageDialogOpen(false);
    toast.success('페이지가 추가되었습니다');
  };

  const handleAddSection = () => {
    if (!selectedPage) {
      toast.error('페이지를 선택해주세요');
      return;
    }

    if (!newSectionTitle) {
      toast.error('섹션 제목을 입력해주세요');
      return;
    }

    const newSection: ItemSection = {
      id: `SECTION-${Date.now()}`,
      title: newSectionTitle,
      description: newSectionDescription || undefined,
      category: newSectionCategory ? newSectionCategory.split(',').map(c => c.trim()) : undefined,
      fields: [],
      order: selectedPage.sections.length + 1,
      isCollapsible: true,
      isCollapsed: false,
      createdAt: new Date().toISOString().split('T')[0]
    };

    addSectionToPage(selectedPage.id, newSection);
    setNewSectionTitle('');
    setNewSectionDescription('');
    setNewSectionCategory('');
    setIsSectionDialogOpen(false);
    toast.success('섹션이 추가되었습니다');
  };

  const handleAddField = () => {
    if (!selectedPage || !selectedSectionForField) {
      toast.error('섹션을 선택해주세요');
      return;
    }

    if (!newFieldName || !newFieldKey) {
      toast.error('항목명과 필드 키를 입력해주세요');
      return;
    }

    const property: ItemFieldProperty = {
      inputType: newFieldInputType,
      required: newFieldRequired,
      row: newFieldRow,
      col: newFieldCol,
      options: newFieldInputType === 'dropdown' ? newFieldOptions.split(',').map(o => o.trim()) : undefined
    };

    const newField: ItemField = {
      id: `FIELD-${Date.now()}`,
      name: newFieldName,
      fieldKey: newFieldKey,
      property,
      category: newFieldCategory ? newFieldCategory.split(',').map(c => c.trim()) : undefined,
      createdAt: new Date().toISOString().split('T')[0]
    };

    addFieldToSection(selectedPage.id, selectedSectionForField, newField);
    setNewFieldName('');
    setNewFieldKey('');
    setNewFieldInputType('textbox');
    setNewFieldRequired(false);
    setNewFieldRow(1);
    setNewFieldCol(1);
    setNewFieldOptions('');
    setNewFieldCategory('');
    setIsFieldDialogOpen(false);
    toast.success('항목이 추가되었습니다');
  };

  const handleDeleteSection = (sectionId: string) => {
    if (!selectedPage) return;
    
    if (confirm('이 섹션을 삭제하시겠습니까?')) {
      deleteSection(selectedPage.id, sectionId);
      toast.success('섹션이 삭제되었습니다');
    }
  };

  const handleDeleteField = (sectionId: string, fieldId: string) => {
    if (!selectedPage) return;
    
    if (confirm('이 항목을 삭제하시겠습니까?')) {
      deleteField(selectedPage.id, sectionId, fieldId);
      toast.success('항목이 삭제되었습니다');
    }
  };

  return (
    <PageLayout>
      <PageHeader
        title="기준관리"
        subtitle="품목기준관리"
        icon={Database}
      />

      <div className="space-y-4">
        {/* 참고 이미지 */}
        <Card>
          <CardHeader>
            <CardTitle>계층구조 설계 참고</CardTitle>
            <CardDescription>페이지 → 섹션 → 항목 → 속성 구조</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-sm mb-2">계층구조 예시</p>
                <img src={img1} alt="계층구조" className="border rounded" />
              </div>
              <div>
                <p className="text-sm mb-2">UI 예시</p>
                <img src={img2} alt="UI 예시" className="border rounded" />
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="grid grid-cols-4 gap-4">
          {/* 왼쪽: 페이지 목록 */}
          <Card className="col-span-1">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">페이지 목록</CardTitle>
                <Dialog open={isPageDialogOpen} onOpenChange={setIsPageDialogOpen}>
                  <DialogTrigger asChild>
                    <Button size="sm" variant="ghost">
                      <Plus className="h-4 w-4" />
                    </Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>페이지 추가</DialogTitle>
                      <DialogDescription>새로운 품목 페이지를 추가합니다</DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4">
                      <div>
                        <Label>페이지명</Label>
                        <Input
                          value={newPageName}
                          onChange={(e) => setNewPageName(e.target.value)}
                          placeholder="예: 품목 등록"
                        />
                      </div>
                      <div>
                        <Label>품목유형</Label>
                        <Select value={newPageItemType} onValueChange={(v: any) => setNewPageItemType(v)}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {ITEM_TYPE_OPTIONS.map(opt => (
                              <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <DialogFooter>
                      <Button variant="outline" onClick={() => setIsPageDialogOpen(false)}>취소</Button>
                      <Button onClick={handleAddPage}>추가</Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>
              </div>
            </CardHeader>
            <CardContent className="space-y-2">
              {itemPages.map(page => (
                <button
                  key={page.id}
                  onClick={() => setSelectedPage(page)}
                  className={`w-full text-left p-2 rounded hover:bg-gray-50 transition-colors ${
                    selectedPage?.id === page.id ? 'bg-blue-50 border border-blue-200' : 'border border-gray-200'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="text-sm">{page.pageName}</div>
                      <div className="text-xs text-gray-500">
                        {ITEM_TYPE_OPTIONS.find(t => t.value === page.itemType)?.label}
                      </div>
                    </div>
                    {page.isActive ? (
                      <Eye className="h-4 w-4 text-green-500" />
                    ) : (
                      <EyeOff className="h-4 w-4 text-gray-400" />
                    )}
                  </div>
                </button>
              ))}
            </CardContent>
          </Card>

          {/* 오른쪽: 계층구조 뷰 */}
          <Card className="col-span-3">
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>{selectedPage?.pageName || '페이지를 선택하세요'}</CardTitle>
                  <CardDescription>
                    {selectedPage && `품목유형: ${ITEM_TYPE_OPTIONS.find(t => t.value === selectedPage.itemType)?.label}`}
                  </CardDescription>
                </div>
                {selectedPage && (
                  <Dialog open={isSectionDialogOpen} onOpenChange={setIsSectionDialogOpen}>
                    <DialogTrigger asChild>
                      <Button size="sm">
                        <Plus className="h-4 w-4 mr-2" />
                        섹션 추가
                      </Button>
                    </DialogTrigger>
                    <DialogContent>
                      <DialogHeader>
                        <DialogTitle>섹션 추가</DialogTitle>
                        <DialogDescription>새로운 섹션을 추가합니다</DialogDescription>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div>
                          <Label>섹션 제목</Label>
                          <Input
                            value={newSectionTitle}
                            onChange={(e) => setNewSectionTitle(e.target.value)}
                            placeholder="예: 기본정보, BOM"
                          />
                        </div>
                        <div>
                          <Label>설명 (선택사항)</Label>
                          <Textarea
                            value={newSectionDescription}
                            onChange={(e) => setNewSectionDescription(e.target.value)}
                            placeholder="섹션 설명"
                          />
                        </div>
                        <div>
                          <Label>카테고리 조건 (선택사항)</Label>
                          <Input
                            value={newSectionCategory}
                            onChange={(e) => setNewSectionCategory(e.target.value)}
                            placeholder="제품,부품 (쉼표로 구분)"
                          />
                          <p className="text-xs text-gray-500 mt-1">특정 카테고리에서만 표시됩니다</p>
                        </div>
                      </div>
                      <DialogFooter>
                        <Button variant="outline" onClick={() => setIsSectionDialogOpen(false)}>취소</Button>
                        <Button onClick={handleAddSection}>추가</Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                )}
              </div>
            </CardHeader>
            <CardContent>
              {selectedPage ? (
                <div className="space-y-4">
                  {/* 계층구조 트리 */}
                  <div className="border rounded-lg p-4 bg-gray-50">
                    <div className="flex items-center gap-2 mb-3">
                      <FolderTree className="h-5 w-5 text-purple-500" />
                      <span className="font-semibold">페이지 1: {selectedPage.pageName}</span>
                    </div>

                    {selectedPage.sections.length === 0 ? (
                      <p className="text-sm text-gray-500 ml-8">섹션을 추가해주세요</p>
                    ) : (
                      selectedPage.sections.map((section, sectionIdx) => (
                        <div key={section.id} className="ml-6 mb-4">
                          <div className="flex items-start gap-2 group">
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <button
                                  onClick={() => toggleSection(section.id)}
                                  className="hover:bg-gray-200 rounded p-1"
                                >
                                  {expandedSections[section.id] ? (
                                    <ChevronDown className="h-4 w-4" />
                                  ) : (
                                    <ChevronRight className="h-4 w-4" />
                                  )}
                                </button>
                                <FileText className="h-4 w-4 text-blue-500" />
                                <span className="font-medium">섹션 {sectionIdx + 1}: {section.title}</span>
                                {section.category && (
                                  <Badge variant="outline" className="text-xs">
                                    {section.category.join(', ')}
                                  </Badge>
                                )}
                              </div>

                              {expandedSections[section.id] && (
                                <div className="ml-8 mt-2 space-y-2">
                                  {section.fields.length === 0 ? (
                                    <p className="text-xs text-gray-500">항목을 추가해주세요</p>
                                  ) : (
                                    section.fields.map((field, fieldIdx) => (
                                      <div key={field.id} className="flex items-start gap-2 text-sm group/field">
                                        <div className="flex-1">
                                          <div className="flex items-center gap-2">
                                            <GripVertical className="h-3 w-3 text-gray-400" />
                                            <span>항목{fieldIdx + 1}: {field.name}</span>
                                          </div>
                                          <div className="ml-5 text-xs text-gray-500 space-y-0.5">
                                            <div>• 입력방식: {INPUT_TYPE_OPTIONS.find(t => t.value === field.property.inputType)?.label}</div>
                                            <div>• 필수: {field.property.required ? '예' : '아니오'}</div>
                                            <div>• 위치: {field.property.row}행 {field.property.col}열</div>
                                            {field.property.options && (
                                              <div>• 옵션: {field.property.options.join(', ')}</div>
                                            )}
                                            {field.category && (
                                              <div>• 카테고리: {field.category.join(', ')}</div>
                                            )}
                                          </div>
                                        </div>
                                        <Button
                                          size="sm"
                                          variant="ghost"
                                          className="opacity-0 group-hover/field:opacity-100"
                                          onClick={() => handleDeleteField(section.id, field.id)}
                                        >
                                          <Trash2 className="h-3 w-3 text-red-500" />
                                        </Button>
                                      </div>
                                    ))
                                  )}
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    className="mt-2"
                                    onClick={() => {
                                      setSelectedSectionForField(section.id);
                                      setIsFieldDialogOpen(true);
                                    }}
                                  >
                                    <Plus className="h-3 w-3 mr-1" />
                                    항목 추가
                                  </Button>
                                </div>
                              )}
                            </div>
                            <Button
                              size="sm"
                              variant="ghost"
                              className="opacity-0 group-hover:opacity-100"
                              onClick={() => handleDeleteSection(section.id)}
                            >
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              ) : (
                <p className="text-center text-gray-500">왼쪽에서 페이지를 선택하세요</p>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* 항목 추가 다이얼로그 */}
      <Dialog open={isFieldDialogOpen} onOpenChange={setIsFieldDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>항목 추가</DialogTitle>
            <DialogDescription>새로운 항목과 속성을 추가합니다</DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-4">
              <div>
                <Label>항목명 *</Label>
                <Input
                  value={newFieldName}
                  onChange={(e) => setNewFieldName(e.target.value)}
                  placeholder="예: 품목코드, 품목명"
                />
              </div>
              <div>
                <Label>필드 키 *</Label>
                <Input
                  value={newFieldKey}
                  onChange={(e) => setNewFieldKey(e.target.value)}
                  placeholder="예: itemCode, itemName"
                />
                <p className="text-xs text-gray-500 mt-1">데이터베이스 필드명 (영문)</p>
              </div>
              <div>
                <Label>입력방식</Label>
                <Select value={newFieldInputType} onValueChange={(v: any) => setNewFieldInputType(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INPUT_TYPE_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              {newFieldInputType === 'dropdown' && (
                <div>
                  <Label>드롭다운 옵션</Label>
                  <Input
                    value={newFieldOptions}
                    onChange={(e) => setNewFieldOptions(e.target.value)}
                    placeholder="제품,부품,원자재 (쉼표로 구분)"
                  />
                </div>
              )}
            </div>
            <div className="space-y-4">
              <div className="flex items-center gap-2">
                <Switch
                  checked={newFieldRequired}
                  onCheckedChange={setNewFieldRequired}
                />
                <Label>필수 항목</Label>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <Label>행 위치</Label>
                  <Input
                    type="number"
                    value={newFieldRow}
                    onChange={(e) => setNewFieldRow(parseInt(e.target.value) || 1)}
                    min={1}
                  />
                </div>
                <div>
                  <Label>열 위치</Label>
                  <Input
                    type="number"
                    value={newFieldCol}
                    onChange={(e) => setNewFieldCol(parseInt(e.target.value) || 1)}
                    min={1}
                  />
                </div>
              </div>
              <div>
                <Label>카테고리 조건 (선택사항)</Label>
                <Input
                  value={newFieldCategory}
                  onChange={(e) => setNewFieldCategory(e.target.value)}
                  placeholder="제품,부품 (쉼표로 구분)"
                />
                <p className="text-xs text-gray-500 mt-1">특정 카테고리에서만 표시됩니다</p>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsFieldDialogOpen(false)}>취소</Button>
            <Button onClick={handleAddField}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}
