import { useState } from 'react';
import { useDeveloperMode } from './contexts/DeveloperModeContext';
import { 
  ChevronDown, 
  ChevronUp, 
  X, 
  Code, 
  Database, 
  Layers, 
  Workflow,
  FileCode,
  CheckCircle,
  Package,
  Activity
} from 'lucide-react';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';

export function DeveloperConsole() {
  const { isDeveloperMode, setIsDeveloperMode, currentMetadata, isConsoleExpanded, setIsConsoleExpanded } = useDeveloperMode();
  const [activeTab, setActiveTab] = useState('api');

  if (!isDeveloperMode) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 z-50 bg-gray-900 text-gray-100 shadow-2xl border-t-2 border-blue-500">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-4 py-2 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center gap-3">
          <Code className="w-5 h-5 text-blue-400" />
          <h3 className="font-semibold">개발자 콘솔</h3>
          {currentMetadata && (
            <>
              <Badge variant="outline" className="bg-blue-900 text-blue-200 border-blue-600">
                {currentMetadata.componentName}
              </Badge>
              <span className="text-sm text-gray-400">{currentMetadata.pagePath}</span>
            </>
          )}
        </div>
        
        <div className="flex items-center gap-2">
          <Button
            size="sm"
            variant="ghost"
            onClick={() => setIsConsoleExpanded(!isConsoleExpanded)}
            className="text-gray-300 hover:text-white hover:bg-gray-700"
          >
            {isConsoleExpanded ? (
              <>
                <ChevronDown className="w-4 h-4 mr-1" />
                최소화
              </>
            ) : (
              <>
                <ChevronUp className="w-4 h-4 mr-1" />
                확장
              </>
            )}
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => setIsDeveloperMode(false)}
            className="text-gray-300 hover:text-white hover:bg-gray-700"
          >
            <X className="w-4 h-4" />
          </Button>
        </div>
      </div>

      {/* 콘텐츠 */}
      {isConsoleExpanded && (
        <div className="overflow-y-auto" style={{ maxHeight: '60vh' }}>
          {!currentMetadata ? (
            <div className="p-8 text-center text-gray-500">
              <Code className="w-16 h-16 mx-auto mb-4 opacity-20" />
              <p>페이지를 선택하면 개발 정보가 표시됩니다.</p>
            </div>
          ) : (
            <Tabs value={activeTab} onValueChange={setActiveTab} className="p-4">
              <TabsList className="bg-gray-800 mb-4">
                <TabsTrigger value="api" className="data-[state=active]:bg-gray-700">
                  <Database className="w-4 h-4 mr-2" />
                  API 설계
                </TabsTrigger>
                <TabsTrigger value="data" className="data-[state=active]:bg-gray-700">
                  <Layers className="w-4 h-4 mr-2" />
                  데이터 구조
                </TabsTrigger>
                <TabsTrigger value="component" className="data-[state=active]:bg-gray-700">
                  <FileCode className="w-4 h-4 mr-2" />
                  컴포넌트
                </TabsTrigger>
                <TabsTrigger value="state" className="data-[state=active]:bg-gray-700">
                  <Activity className="w-4 h-4 mr-2" />
                  상태 관리
                </TabsTrigger>
                <TabsTrigger value="db" className="data-[state=active]:bg-gray-700">
                  <Database className="w-4 h-4 mr-2" />
                  DB 스키마
                </TabsTrigger>
                <TabsTrigger value="logic" className="data-[state=active]:bg-gray-700">
                  <Workflow className="w-4 h-4 mr-2" />
                  비즈니스 로직
                </TabsTrigger>
              </TabsList>

              {/* API 설계 탭 */}
              <TabsContent value="api" className="space-y-4">
                <div className="text-sm text-gray-400 mb-4">{currentMetadata.description}</div>
                
                {currentMetadata.apis && currentMetadata.apis.length > 0 ? (
                  currentMetadata.apis.map((api, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <Badge 
                            variant={
                              api.method === 'GET' ? 'default' :
                              api.method === 'POST' ? 'secondary' :
                              api.method === 'PUT' ? 'outline' :
                              api.method === 'DELETE' ? 'destructive' : 'default'
                            }
                            className="font-mono"
                          >
                            {api.method}
                          </Badge>
                          <code className="text-sm text-blue-400">{api.endpoint}</code>
                        </div>
                        <p className="text-sm text-gray-400 mt-2">{api.description}</p>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        {api.pathParams && api.pathParams.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Path Parameters</h4>
                            <div className="bg-gray-900 rounded p-3 space-y-1">
                              {api.pathParams.map((param, i) => (
                                <div key={i} className="text-xs">
                                  <code className="text-yellow-400">{param.name}</code>
                                  <span className="text-gray-500"> : </span>
                                  <span className="text-green-400">{param.type}</span>
                                  <span className="text-gray-400"> - {param.description}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        {api.queryParams && api.queryParams.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Query Parameters</h4>
                            <div className="bg-gray-900 rounded p-3 space-y-1">
                              {api.queryParams.map((param, i) => (
                                <div key={i} className="text-xs">
                                  <code className="text-yellow-400">{param.name}</code>
                                  {param.required && <span className="text-red-400">*</span>}
                                  <span className="text-gray-500"> : </span>
                                  <span className="text-green-400">{param.type}</span>
                                  <span className="text-gray-400"> - {param.description}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        {api.requestBody && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Request Body</h4>
                            <pre className="bg-gray-900 rounded p-3 text-xs overflow-x-auto">
                              <code className="text-green-300">{JSON.stringify(api.requestBody, null, 2)}</code>
                            </pre>
                          </div>
                        )}
                        
                        {api.responseBody && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Response Body</h4>
                            <pre className="bg-gray-900 rounded p-3 text-xs overflow-x-auto">
                              <code className="text-blue-300">{JSON.stringify(api.responseBody, null, 2)}</code>
                            </pre>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">API 정보가 없습니다.</div>
                )}
              </TabsContent>

              {/* 데이터 구조 탭 */}
              <TabsContent value="data" className="space-y-4">
                {currentMetadata.dataStructures && currentMetadata.dataStructures.length > 0 ? (
                  currentMetadata.dataStructures.map((structure, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <Badge variant="outline" className="font-mono">{structure.type}</Badge>
                          <code className="text-sm text-blue-400">{structure.name}</code>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        <div className="bg-gray-900 rounded p-3 space-y-1">
                          {structure.fields.map((field, i) => (
                            <div key={i} className="text-xs">
                              <code className="text-yellow-400">{field.name}</code>
                              {field.required && <span className="text-red-400">*</span>}
                              <span className="text-gray-500"> : </span>
                              <span className="text-green-400">{field.type}</span>
                              <span className="text-gray-400"> - {field.description}</span>
                            </div>
                          ))}
                        </div>
                        
                        {structure.example && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Example</h4>
                            <pre className="bg-gray-900 rounded p-3 text-xs overflow-x-auto">
                              <code className="text-blue-300">{JSON.stringify(structure.example, null, 2)}</code>
                            </pre>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">데이터 구조 정보가 없습니다.</div>
                )}
              </TabsContent>

              {/* 컴포넌트 탭 */}
              <TabsContent value="component" className="space-y-4">
                {currentMetadata.components && currentMetadata.components.length > 0 ? (
                  currentMetadata.components.map((component, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <FileCode className="w-4 h-4 text-blue-400" />
                          <code className="text-sm text-blue-400">{component.name}</code>
                          <span className="text-xs text-gray-500">{component.path}</span>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        {component.props && component.props.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">Props</h4>
                            <div className="bg-gray-900 rounded p-3 space-y-1">
                              {component.props.map((prop, i) => (
                                <div key={i} className="text-xs">
                                  <code className="text-yellow-400">{prop.name}</code>
                                  {prop.required && <span className="text-red-400">*</span>}
                                  <span className="text-gray-500"> : </span>
                                  <span className="text-green-400">{prop.type}</span>
                                  <span className="text-gray-400"> - {prop.description}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        {component.children && component.children.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">자식 컴포넌트</h4>
                            <div className="flex flex-wrap gap-2">
                              {component.children.map((child, i) => (
                                <Badge key={i} variant="secondary" className="bg-gray-700">
                                  {child}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">컴포넌트 정보가 없습니다.</div>
                )}
                
                {currentMetadata.dependencies && currentMetadata.dependencies.length > 0 && (
                  <Card className="bg-gray-800 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2">
                        <Package className="w-4 h-4" />
                        의존성
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="bg-gray-900 rounded p-3 space-y-2">
                        {currentMetadata.dependencies.map((dep, i) => (
                          <div key={i} className="text-xs">
                            <code className="text-blue-400">{dep.package}</code>
                            {dep.version && <span className="text-gray-500">@{dep.version}</span>}
                            <span className="text-gray-400 ml-2">- {dep.usage}</span>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                )}
              </TabsContent>

              {/* 상태 관리 탭 */}
              <TabsContent value="state" className="space-y-4">
                {currentMetadata.stateManagement && currentMetadata.stateManagement.length > 0 ? (
                  currentMetadata.stateManagement.map((state, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <Badge variant={state.type === 'Context' ? 'default' : 'secondary'}>
                            {state.type}
                          </Badge>
                          <code className="text-sm text-blue-400">{state.name}</code>
                        </div>
                        <p className="text-sm text-gray-400 mt-2">{state.description}</p>
                      </CardHeader>
                      {state.methods && state.methods.length > 0 && (
                        <CardContent>
                          <h4 className="text-sm font-semibold text-gray-300 mb-2">메서드</h4>
                          <div className="bg-gray-900 rounded p-3 space-y-1">
                            {state.methods.map((method, i) => (
                              <div key={i} className="text-xs">
                                <code className="text-green-400">{method}</code>
                              </div>
                            ))}
                          </div>
                        </CardContent>
                      )}
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">상태 관리 정보가 없습니다.</div>
                )}
              </TabsContent>

              {/* DB 스키마 탭 */}
              <TabsContent value="db" className="space-y-4">
                {currentMetadata.dbSchema && currentMetadata.dbSchema.length > 0 ? (
                  currentMetadata.dbSchema.map((schema, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <Database className="w-4 h-4 text-blue-400" />
                          <code className="text-sm text-blue-400">{schema.tableName}</code>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-3">
                        <div>
                          <h4 className="text-sm font-semibold text-gray-300 mb-2">컬럼</h4>
                          <div className="bg-gray-900 rounded p-3 space-y-1">
                            {schema.columns.map((col, i) => (
                              <div key={i} className="text-xs">
                                <code className="text-yellow-400">{col.name}</code>
                                {col.key && <Badge variant="outline" className="ml-2 text-xs py-0">{col.key}</Badge>}
                                <span className="text-gray-500"> : </span>
                                <span className="text-green-400">{col.type}</span>
                                {!col.nullable && <span className="text-red-400"> NOT NULL</span>}
                                <span className="text-gray-400"> - {col.description}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                        
                        {schema.indexes && schema.indexes.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">인덱스</h4>
                            <div className="flex flex-wrap gap-2">
                              {schema.indexes.map((idx, i) => (
                                <Badge key={i} variant="secondary" className="bg-gray-700 text-xs">
                                  {idx}
                                </Badge>
                              ))}
                            </div>
                          </div>
                        )}
                        
                        {schema.relations && schema.relations.length > 0 && (
                          <div>
                            <h4 className="text-sm font-semibold text-gray-300 mb-2">관계</h4>
                            <div className="bg-gray-900 rounded p-3 space-y-1">
                              {schema.relations.map((rel, i) => (
                                <div key={i} className="text-xs">
                                  <Badge variant="outline" className="text-xs py-0">{rel.type}</Badge>
                                  <span className="text-gray-400 ml-2">{rel.table}</span>
                                  <span className="text-gray-500"> - {rel.description}</span>
                                </div>
                              ))}
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">DB 스키마 정보가 없습니다.</div>
                )}
              </TabsContent>

              {/* 비즈니스 로직 탭 */}
              <TabsContent value="logic" className="space-y-4">
                {currentMetadata.businessLogic && currentMetadata.businessLogic.length > 0 ? (
                  currentMetadata.businessLogic.map((logic, index) => (
                    <Card key={index} className="bg-gray-800 border-gray-700">
                      <CardHeader className="pb-3">
                        <div className="flex items-center gap-3">
                          <Workflow className="w-4 h-4 text-blue-400" />
                          <span className="text-sm font-semibold">{logic.name}</span>
                        </div>
                        <p className="text-sm text-gray-400 mt-2">{logic.description}</p>
                      </CardHeader>
                      <CardContent>
                        <div className="space-y-2">
                          {logic.steps.map((step, i) => (
                            <div key={i} className="flex items-start gap-3">
                              <div className="flex items-center justify-center w-6 h-6 rounded-full bg-blue-900 text-blue-300 text-xs font-semibold flex-shrink-0">
                                {i + 1}
                              </div>
                              <p className="text-sm text-gray-300 pt-0.5">{step}</p>
                            </div>
                          ))}
                        </div>
                      </CardContent>
                    </Card>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-8">비즈니스 로직 정보가 없습니다.</div>
                )}
                
                {currentMetadata.validations && currentMetadata.validations.length > 0 && (
                  <Card className="bg-gray-800 border-gray-700">
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2">
                        <CheckCircle className="w-4 h-4" />
                        유효성 검사
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-3">
                        {currentMetadata.validations.map((validation, i) => (
                          <div key={i} className="bg-gray-900 rounded p-3">
                            <code className="text-yellow-400 text-sm">{validation.field}</code>
                            <div className="mt-2 space-y-1">
                              {validation.rules.map((rule, j) => (
                                <div key={j} className="text-xs text-gray-400">
                                  • {rule}
                                  {validation.errorMessages[j] && (
                                    <span className="text-red-400 ml-2">→ {validation.errorMessages[j]}</span>
                                  )}
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                )}
              </TabsContent>
            </Tabs>
          )}
        </div>
      )}
    </div>
  );
}
