import { useState } from 'react';
import { Code2, FileCode, Server, Terminal, Database, GitBranch } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Label } from './ui/label';
import { Switch } from './ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';

interface PageMetadata {
  componentName?: string;
  description?: string;
  currentTab?: string;
  tabMetadata?: {
    dataSource: string;
    interface: string;
    contextMethods: string[];
    storageKey: string;
    dependencies: string[];
    usedIn: string[];
  };
  dataCount?: number;
  activeFilters?: Record<string, any>;
}

interface DeveloperModePanelProps {
  pageMetadata?: PageMetadata;
}

export function DeveloperModePanel({ pageMetadata }: DeveloperModePanelProps) {
  const [isDeveloperMode, setIsDeveloperMode] = useState(false);

  return (
    <Card className="border-purple-200 bg-gradient-to-br from-purple-50 to-indigo-50">
      <CardContent className="pt-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Code2 className="h-5 w-5 text-purple-600" />
            <div>
              <h3 className="font-semibold text-purple-900">개발자 모드</h3>
              <p className="text-xs text-purple-700">백엔드 및 프론트엔드 개발자를 위한 기술 문서</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Label htmlFor="dev-mode" className="text-sm text-purple-900 cursor-pointer">
              {isDeveloperMode ? '활성화됨' : '비활성화됨'}
            </Label>
            <Switch
              id="dev-mode"
              checked={isDeveloperMode}
              onCheckedChange={setIsDeveloperMode}
            />
          </div>
        </div>

        {isDeveloperMode && (
          <div className="space-y-6 mt-6">
            {/* 현재 화면 메타데이터 표시 */}
            {pageMetadata && (
              <Card className="border-indigo-300 bg-gradient-to-br from-indigo-50 to-purple-50">
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2">
                    <Database className="h-4 w-4" />
                    현재 화면 정보
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-xs font-semibold text-slate-700 mb-1">컴포넌트명</div>
                      <Badge variant="outline" className="bg-blue-50 text-blue-700">
                        {pageMetadata.componentName || 'Unknown'}
                      </Badge>
                    </div>
                    {pageMetadata.currentTab && (
                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-1">현재 탭</div>
                        <Badge variant="outline" className="bg-green-50 text-green-700">
                          {pageMetadata.currentTab}
                        </Badge>
                      </div>
                    )}
                  </div>

                  {pageMetadata.description && (
                    <div>
                      <div className="text-xs font-semibold text-slate-700 mb-1">설명</div>
                      <p className="text-xs text-slate-600">{pageMetadata.description}</p>
                    </div>
                  )}

                  {pageMetadata.tabMetadata && (
                    <>
                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">데이터 소스</div>
                        <div className="bg-slate-900 text-green-400 p-3 rounded-lg font-mono text-xs">
                          {pageMetadata.tabMetadata.dataSource}
                        </div>
                      </div>

                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">TypeScript 인터페이스</div>
                        <div className="bg-slate-900 text-green-400 p-3 rounded-lg font-mono text-xs overflow-x-auto">
                          {pageMetadata.tabMetadata.interface}
                        </div>
                      </div>

                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">Context 메서드</div>
                        <div className="flex flex-wrap gap-2">
                          {pageMetadata.tabMetadata.contextMethods.map((method) => (
                            <Badge key={method} variant="outline" className="bg-purple-50 text-purple-700 font-mono text-xs">
                              {method}()
                            </Badge>
                          ))}
                        </div>
                      </div>

                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">localStorage 키</div>
                        <Badge variant="outline" className="bg-orange-50 text-orange-700 font-mono">
                          {pageMetadata.tabMetadata.storageKey}
                        </Badge>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <div className="text-xs font-semibold text-slate-700 mb-2">의존성</div>
                          <div className="flex flex-wrap gap-1">
                            {pageMetadata.tabMetadata.dependencies.map((dep) => (
                              <Badge key={dep} variant="secondary" className="text-xs">
                                {dep}
                              </Badge>
                            ))}
                          </div>
                        </div>
                        <div>
                          <div className="text-xs font-semibold text-slate-700 mb-2">사용 위치</div>
                          <div className="flex flex-wrap gap-1">
                            {pageMetadata.tabMetadata.usedIn.map((component) => (
                              <Badge key={component} variant="secondary" className="text-xs font-mono">
                                {component}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      </div>
                    </>
                  )}

                  {pageMetadata.activeFilters && (
                    <div>
                      <div className="text-xs font-semibold text-slate-700 mb-2">현재 상태</div>
                      <div className="grid grid-cols-3 gap-2">
                        {Object.entries(pageMetadata.activeFilters).map(([key, value]) => (
                          <div key={key} className="bg-slate-100 rounded-lg p-2">
                            <div className="text-xs text-slate-600">{key}</div>
                            <div className="font-semibold text-sm">
                              {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            <Tabs defaultValue="backend" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="backend" className="gap-2">
                  <Server className="h-4 w-4" />
                  백엔드 개발자
                </TabsTrigger>
                <TabsTrigger value="frontend" className="gap-2">
                  <FileCode className="h-4 w-4" />
                  프론트엔드 개발자
                </TabsTrigger>
              </TabsList>

              {/* 백엔드 개발자 탭 */}
              <TabsContent value="backend" className="space-y-4 mt-4">
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm flex items-center gap-2">
                      <Terminal className="h-4 w-4" />
                      API 엔드포인트 설계
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-2 overflow-x-auto">
                      <div><span className="text-blue-400">GET</span> /api/v1/item-master/units</div>
                      <div><span className="text-green-400">POST</span> /api/v1/item-master/units</div>
                      <div><span className="text-yellow-400">PUT</span> /api/v1/item-master/units/:id</div>
                      <div><span className="text-red-400">DELETE</span> /api/v1/item-master/units/:id</div>
                      <div className="mt-2 pt-2 border-t border-slate-700">
                        <div><span className="text-blue-400">GET</span> /api/v1/item-master/materials</div>
                        <div><span className="text-blue-400">GET</span> /api/v1/item-master/surface-treatments</div>
                        <div><span className="text-blue-400">GET</span> /api/v1/item-master/part-types</div>
                        <div><span className="text-blue-400">GET</span> /api/v1/item-master/part-usages</div>
                        <div><span className="text-blue-400">GET</span> /api/v1/item-master/guide-rail-options</div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">데이터베이스 스키마</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div className="text-purple-400">-- ItemUnit Table</div>
                      <div><span className="text-yellow-400">CREATE TABLE</span> item_units (</div>
                      <div className="pl-4">id <span className="text-blue-400">VARCHAR(50)</span> PRIMARY KEY,</div>
                      <div className="pl-4">unit_code <span className="text-blue-400">VARCHAR(20)</span> UNIQUE NOT NULL,</div>
                      <div className="pl-4">unit_name <span className="text-blue-400">VARCHAR(50)</span> NOT NULL,</div>
                      <div className="pl-4">description <span className="text-blue-400">TEXT</span>,</div>
                      <div className="pl-4">is_active <span className="text-blue-400">BOOLEAN</span> DEFAULT TRUE,</div>
                      <div className="pl-4">created_at <span className="text-blue-400">TIMESTAMP</span> DEFAULT NOW(),</div>
                      <div className="pl-4">updated_at <span className="text-blue-400">TIMESTAMP</span></div>
                      <div>);</div>
                      
                      <div className="mt-3 text-purple-400">-- ItemMaterial Table</div>
                      <div><span className="text-yellow-400">CREATE TABLE</span> item_materials (</div>
                      <div className="pl-4">id <span className="text-blue-400">VARCHAR(50)</span> PRIMARY KEY,</div>
                      <div className="pl-4">material_code <span className="text-blue-400">VARCHAR(20)</span> UNIQUE NOT NULL,</div>
                      <div className="pl-4">material_name <span className="text-blue-400">VARCHAR(100)</span> NOT NULL,</div>
                      <div className="pl-4">material_type <span className="text-blue-400">ENUM</span>('STEEL', 'ALUMINUM', 'PLASTIC', 'OTHER'),</div>
                      <div className="pl-4">thickness <span className="text-blue-400">VARCHAR(20)</span>,</div>
                      <div className="pl-4">is_active <span className="text-blue-400">BOOLEAN</span> DEFAULT TRUE</div>
                      <div>);</div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">요청/응답 예시</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">POST /api/v1/item-master/units</div>
                        <div className="bg-slate-900 text-green-400 p-3 rounded-lg font-mono text-xs overflow-x-auto">
                          <pre>{JSON.stringify({
                            unitCode: "EA",
                            unitName: "개",
                            description: "개별 단위",
                            isActive: true
                          }, null, 2)}</pre>
                        </div>
                      </div>
                      <div>
                        <div className="text-xs font-semibold text-slate-700 mb-2">Response 200 OK</div>
                        <div className="bg-slate-900 text-green-400 p-3 rounded-lg font-mono text-xs overflow-x-auto">
                          <pre>{JSON.stringify({
                            success: true,
                            data: {
                              id: "UNIT-1234567890",
                              unitCode: "EA",
                              unitName: "개",
                              description: "개별 단위",
                              isActive: true,
                              createdAt: "2025-01-15T10:30:00Z"
                            }
                          }, null, 2)}</pre>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">인덱스 권장사항</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div><span className="text-yellow-400">CREATE INDEX</span> idx_unit_code ON item_units(unit_code);</div>
                      <div><span className="text-yellow-400">CREATE INDEX</span> idx_material_code ON item_materials(material_code);</div>
                      <div><span className="text-yellow-400">CREATE INDEX</span> idx_is_active ON item_units(is_active);</div>
                      <div><span className="text-yellow-400">CREATE INDEX</span> idx_part_type ON part_type_options(part_type, is_active);</div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              {/* 프론트엔드 개발자 탭 */}
              <TabsContent value="frontend" className="space-y-4 mt-4">
                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">TypeScript 인터페이스</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div><span className="text-purple-400">interface</span> <span className="text-yellow-400">ItemUnit</span> {'{'}</div>
                      <div className="pl-4">id: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">unitCode: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">unitName: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">description?: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">isActive: <span className="text-blue-400">boolean</span>;</div>
                      <div className="pl-4">createdAt?: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">updatedAt?: <span className="text-blue-400">string</span>;</div>
                      <div>{'}'}</div>
                      
                      <div className="mt-3"><span className="text-purple-400">interface</span> <span className="text-yellow-400">ItemMaterial</span> {'{'}</div>
                      <div className="pl-4">id: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">materialCode: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">materialName: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">materialType: <span className="text-blue-400">'STEEL' | 'ALUMINUM' | 'PLASTIC' | 'OTHER'</span>;</div>
                      <div className="pl-4">thickness?: <span className="text-blue-400">string</span>;</div>
                      <div className="pl-4">isActive: <span className="text-blue-400">boolean</span>;</div>
                      <div>{'}'}</div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">React Hook 사용법</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div><span className="text-purple-400">import</span> {'{ useData }'} <span className="text-purple-400">from</span> <span className="text-orange-400">'./contexts/DataContext'</span>;</div>
                      <div className="mt-2"><span className="text-purple-400">const</span> {'{'}</div>
                      <div className="pl-4">itemUnits,</div>
                      <div className="pl-4">addItemUnit,</div>
                      <div className="pl-4">updateItemUnit,</div>
                      <div className="pl-4">deleteItemUnit</div>
                      <div>{'}'} = <span className="text-yellow-400">useData</span>();</div>
                      
                      <div className="mt-3 text-slate-500">// 단위 추가</div>
                      <div><span className="text-purple-400">const</span> newUnit = {'{'}</div>
                      <div className="pl-4">id: <span className="text-orange-400">'UNIT-' + Date.now()</span>,</div>
                      <div className="pl-4">unitCode: <span className="text-orange-400">'EA'</span>,</div>
                      <div className="pl-4">unitName: <span className="text-orange-400">'개'</span>,</div>
                      <div className="pl-4">isActive: <span className="text-blue-400">true</span></div>
                      <div>{'};'}</div>
                      <div><span className="text-yellow-400">addItemUnit</span>(newUnit);</div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">컴포넌트 구조</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-2 text-xs">
                      <div className="flex items-start gap-2">
                        <Badge variant="outline" className="bg-blue-50 text-blue-700">PageLayout</Badge>
                        <span className="text-muted-foreground">- 전체 페이지 레이아웃 템플릿</span>
                      </div>
                      <div className="flex items-start gap-2 pl-4">
                        <Badge variant="outline" className="bg-green-50 text-green-700">PageHeader</Badge>
                        <span className="text-muted-foreground">- 제목, 설명, 아이콘 표시</span>
                      </div>
                      <div className="flex items-start gap-2 pl-4">
                        <Badge variant="outline" className="bg-purple-50 text-purple-700">Card</Badge>
                        <span className="text-muted-foreground">- 안내 메시지 및 탭 컨테이너</span>
                      </div>
                      <div className="flex items-start gap-2 pl-8">
                        <Badge variant="outline" className="bg-orange-50 text-orange-700">Tabs</Badge>
                        <span className="text-muted-foreground">- 단위/재질/표면처리 등 탭 전환</span>
                      </div>
                      <div className="flex items-start gap-2 pl-12">
                        <Badge variant="outline" className="bg-pink-50 text-pink-700">Table</Badge>
                        <span className="text-muted-foreground">- 데이터 목록 표시</span>
                      </div>
                      <div className="flex items-start gap-2 pl-4">
                        <Badge variant="outline" className="bg-indigo-50 text-indigo-700">Dialog</Badge>
                        <span className="text-muted-foreground">- 추가/수정 폼 모달</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">상태 관리</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div className="text-slate-500">// 로컬 상태</div>
                      <div><span className="text-purple-400">const</span> [currentTab, setCurrentTab] = <span className="text-yellow-400">useState</span>(<span className="text-orange-400">'unit'</span>);</div>
                      <div><span className="text-purple-400">const</span> [formData, setFormData] = <span className="text-yellow-400">useState</span>({'{}'});</div>
                      <div><span className="text-purple-400">const</span> [isDialogOpen, setIsDialogOpen] = <span className="text-yellow-400">useState</span>(<span className="text-blue-400">false</span>);</div>
                      
                      <div className="mt-3 text-slate-500">// 전역 상태 (DataContext)</div>
                      <div><span className="text-purple-400">const</span> {'{ itemUnits, itemMaterials }'} = <span className="text-yellow-400">useData</span>();</div>
                      
                      <div className="mt-3 text-slate-500">// localStorage 영속화</div>
                      <div><span className="text-purple-400">useEffect</span>(() =&gt; {'{'}</div>
                      <div className="pl-4">localStorage.<span className="text-yellow-400">setItem</span>(<span className="text-orange-400">'itemUnits'</span>, JSON.<span className="text-yellow-400">stringify</span>(itemUnits));</div>
                      <div>{'}, [itemUnits]);'}</div>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-3">
                    <CardTitle className="text-sm">유효성 검사</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="bg-slate-900 text-green-400 p-4 rounded-lg font-mono text-xs space-y-1 overflow-x-auto">
                      <div><span className="text-purple-400">const</span> <span className="text-yellow-400">validateUnit</span> = (data: ItemUnit) =&gt; {'{'}</div>
                      <div className="pl-4"><span className="text-purple-400">if</span> (!data.unitCode || !data.unitName) {'{'}</div>
                      <div className="pl-8"><span className="text-yellow-400">toast</span>.<span className="text-red-400">error</span>(<span className="text-orange-400">'필수 필드를 입력하세요'</span>);</div>
                      <div className="pl-8"><span className="text-purple-400">return</span> <span className="text-blue-400">false</span>;</div>
                      <div className="pl-4">{'}'}</div>
                      <div className="pl-4"><span className="text-purple-400">return</span> <span className="text-blue-400">true</span>;</div>
                      <div>{'};'}</div>
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>
          </div>
        )}
      </CardContent>
    </Card>
  );
}