import { useState, useEffect } from 'react';
import { PageLayout } from './organisms/PageLayout';
import { PageHeader } from './organisms/PageHeader';
import { useData } from './contexts/DataContext';
import type { ItemPage, ItemField } from './contexts/DataContext';
import { 
  TestTube,
  Save,
  RotateCcw
} from 'lucide-react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import { Badge } from './ui/badge';
import { Checkbox } from './ui/checkbox';
import { toast } from 'sonner@2.0.3';

const ITEM_TYPE_LABELS: Record<string, string> = {
  'FG': '제품',
  'PT': '부품',
  'SM': '부자재',
  'RM': '원자재',
  'CS': '소모품'
};

export function ItemTestPage() {
  const { itemPages } = useData();
  
  const [selectedPageId, setSelectedPageId] = useState<string | null>(null);
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 모든 활성 페이지
  const availablePages = itemPages.filter(p => p.isActive);

  // 현재 선택된 페이지
  const selectedPage = selectedPageId 
    ? itemPages.find(p => p.id === selectedPageId) || null
    : null;

  // 페이지 선택 시 폼 데이터 초기화
  useEffect(() => {
    if (selectedPage) {
      setFormData({});
    }
  }, [selectedPageId]);

  const handleFieldChange = (fieldKey: string, value: any) => {
    setFormData(prev => ({ ...prev, [fieldKey]: value }));
  };

  // 조건부 항목 표시 여부 확인
  const shouldShowField = (field: ItemField): boolean => {
    if (!field.displayCondition) return true;
    
    const conditionFieldValue = formData[field.displayCondition.fieldKey];
    return conditionFieldValue === field.displayCondition.expectedValue;
  };

  // 필드 렌더링
  const renderField = (field: ItemField) => {
    if (!shouldShowField(field)) {
      return null;
    }

    const value = formData[field.fieldKey] || '';
    const { inputType, required, options } = field.property;

    return (
      <div key={field.id}>
        <Label className="flex items-center gap-1">
          {field.name}
          {required && <span className="text-red-500">*</span>}
        </Label>
        
        {inputType === 'textbox' && (
          <Input
            value={value}
            onChange={(e) => handleFieldChange(field.fieldKey, e.target.value)}
            placeholder={`${field.name}을(를) 입력하세요`}
          />
        )}
        
        {inputType === 'number' && (
          <Input
            type="number"
            value={value}
            onChange={(e) => handleFieldChange(field.fieldKey, e.target.value)}
            placeholder={`${field.name}을(를) 입력하세요`}
          />
        )}
        
        {inputType === 'date' && (
          <Input
            type="date"
            value={value}
            onChange={(e) => handleFieldChange(field.fieldKey, e.target.value)}
          />
        )}
        
        {inputType === 'textarea' && (
          <Textarea
            value={value}
            onChange={(e) => handleFieldChange(field.fieldKey, e.target.value)}
            placeholder={`${field.name}을(를) 입력하세요`}
            rows={3}
          />
        )}
        
        {inputType === 'dropdown' && options && (
          <Select value={value} onValueChange={(v) => handleFieldChange(field.fieldKey, v)}>
            <SelectTrigger>
              <SelectValue placeholder={`${field.name}을(를) 선택하세요`} />
            </SelectTrigger>
            <SelectContent>
              {options.map((option, index) => (
                <SelectItem key={index} value={option}>{option}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        
        {inputType === 'checkbox' && (
          <div className="flex items-center space-x-2">
            <Checkbox
              checked={value === true || value === 'true'}
              onCheckedChange={(checked) => handleFieldChange(field.fieldKey, checked)}
            />
            <label className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
              사용
            </label>
          </div>
        )}
        
        {field.displayCondition && (
          <p className="text-xs text-muted-foreground mt-1">
            조건부 항목: {field.displayCondition.fieldKey} = {field.displayCondition.expectedValue}
          </p>
        )}
      </div>
    );
  };

  const handleSave = () => {
    if (!selectedPage) return;

    // 필수 항목 검증
    const missingFields: string[] = [];
    selectedPage.sections.forEach(section => {
      section.fields.forEach(field => {
        if (field.property.required && shouldShowField(field)) {
          const value = formData[field.fieldKey];
          if (!value || value === '') {
            missingFields.push(field.name);
          }
        }
      });
    });

    if (missingFields.length > 0) {
      toast.error(`다음 필수 항목을 입력해주세요: ${missingFields.join(', ')}`);
      return;
    }

    // 저장 로직 (실제로는 DataContext에 저장 함수를 만들어야 함)
    console.log('저장할 데이터:', formData);
    toast.success('품목 정보가 저장되었습니다');
  };

  const handleReset = () => {
    setFormData({});
    toast.info('입력 내용이 초기화되었습니다');
  };

  // 페이지가 선택되지 않은 경우
  if (!selectedPageId || !selectedPage) {
    return (
      <PageLayout>
        <PageHeader
          title="품목테스트"
          description="계층구조 기반으로 동적 생성된 품목 입력 폼을 테스트합니다"
          icon={TestTube}
        />

        <Card>
          <CardHeader>
            <CardTitle>페이지 선택</CardTitle>
          </CardHeader>
          <CardContent>
            {availablePages.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-muted-foreground mb-2">등록된 페이지가 없습니다</p>
                <p className="text-sm text-muted-foreground">
                  기준정보 &gt; 품목기준관리 &gt; 계층구조 탭에서 먼저 페이지를 생성해주세요.
                </p>
              </div>
            ) : (
              <Select value={selectedPageId || undefined} onValueChange={(v) => setSelectedPageId(v)}>
                <SelectTrigger>
                  <SelectValue placeholder="페이지를 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  {availablePages.map((page) => (
                    <SelectItem key={page.id} value={page.id}>
                      <div className="flex items-center gap-2">
                        <Badge variant="secondary" className="text-xs">
                          {ITEM_TYPE_LABELS[page.itemType]}
                        </Badge>
                        {page.pageName}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </CardContent>
        </Card>
      </PageLayout>
    );
  }

  // 페이지가 선택된 경우 - 품목관리와 동일한 스타일
  return (
    <PageLayout>
      <PageHeader
        title="품목테스트"
        description="계층구조 기반으로 동적 생성된 품목 입력 폼을 테스트합니다"
        icon={TestTube}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => setSelectedPageId(null)}>
              페이지 변경
            </Button>
          </div>
        }
      />

      {/* 선택된 페이지 정보 */}
      <div className="flex items-center gap-2 mb-4">
        <Badge variant="secondary">{ITEM_TYPE_LABELS[selectedPage.itemType]}</Badge>
        <span className="text-sm text-muted-foreground">|</span>
        <span className="text-sm font-medium">{selectedPage.pageName}</span>
      </div>

      {/* 섹션별 카드 렌더링 */}
      {selectedPage.sections.length === 0 ? (
        <Card>
          <CardContent className="text-center py-8">
            <p className="text-muted-foreground">
              섹션이 없습니다. 기준관리에서 섹션을 추가해주세요.
            </p>
          </CardContent>
        </Card>
      ) : (
        <>
          {selectedPage.sections.map((section) => {
            // 섹션에 표시할 필드가 있는지 확인
            const visibleFields = section.fields.filter(shouldShowField);
            
            return (
              <Card key={section.id}>
                <CardHeader>
                  <CardTitle>{section.title}</CardTitle>
                  {section.description && (
                    <p className="text-sm text-muted-foreground mt-1">{section.description}</p>
                  )}
                </CardHeader>
                <CardContent className="space-y-4">
                  {section.fields.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-4">
                      항목이 없습니다
                    </p>
                  ) : visibleFields.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-4">
                      조건에 맞는 항목이 없습니다
                    </p>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {section.fields.map(renderField)}
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}

          {/* 하단 액션 버튼 */}
          <div className="flex justify-end gap-2 mt-6">
            <Button variant="outline" onClick={handleReset}>
              <RotateCcw className="h-4 w-4 mr-2" />
              초기화
            </Button>
            <Button onClick={handleSave}>
              <Save className="h-4 w-4 mr-2" />
              저장
            </Button>
          </div>
        </>
      )}
    </PageLayout>
  );
}