"use client"

import * as React from "react"
import { useState } from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle
} from "@/components/ui/sheet"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from "@/components/ui/table"
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger
} from "@/components/ui/tabs"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from "@/components/ui/card"
import type { TagTypeClassFormMappings } from "@/db/schema/vendorData" // or your actual type
import { fetchFormMetadata, FormColumn } from "@/lib/forms/services"

// 옵션을 표시하기 위한 새로운 컴포넌트
const CollapsibleOptions = ({ options }: { options?: string[] }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  
  // 옵션이 없거나 5개 이하인 경우 모두 표시
  if (!options || options.length <= 5) {
    return (
      <div className="flex flex-wrap gap-1">
        {options?.map((option) => (
          <Badge key={option} variant="outline" className="text-xs">
            {option}
          </Badge>
        )) || "-"}
      </div>
    );
  }
  
  // 더 많은 옵션이 있는 경우 접었다 펼칠 수 있게 함
  return (
    <div>
      <div className="flex flex-wrap gap-1 mb-1">
        {isExpanded 
          ? options.map((option) => (
              <Badge key={option} variant="outline" className="text-xs">
                {option}
              </Badge>
            ))
          : options.slice(0, 3).map((option) => (
              <Badge key={option} variant="outline" className="text-xs">
                {option}
              </Badge>
            ))
        }
        {!isExpanded && (
          <Badge variant="outline" className="text-xs bg-muted">
            +{options.length - 3} more
          </Badge>
        )}
      </div>
      <Button
        variant="ghost" 
        size="sm" 
        className="h-6 text-xs px-2 py-0"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        {isExpanded ? "Show less" : "Show all"}
      </Button>
    </div>
  );
};

interface ViewMetasProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  form: TagTypeClassFormMappings | null
}

export function ViewMetas({ open, onOpenChange, form }: ViewMetasProps) {
  // metadata & loading
  const [metadata, setMetadata] = React.useState<{
    formName: string
    formCode: string
    columns: FormColumn[]
  } | null>(null)
  const [loading, setLoading] = React.useState(false)

  // Group columns by type for better organization
  const groupedColumns = React.useMemo(() => {
    if (!metadata?.columns) return {}
    
    return metadata.columns.reduce((acc, column) => {
      const type = column.type
      if (!acc[type]) {
        acc[type] = []
      }
      acc[type].push(column)
      return acc
    }, {} as Record<string, FormColumn[]>)
  }, [metadata])

  // Types for the tabs
  const columnTypes = React.useMemo(() => {
    return Object.keys(groupedColumns)
  }, [groupedColumns])

  // Fetch metadata when form changes and dialog is opened
  React.useEffect(() => {
    async function fetchMeta() {
      if (!form || !open) return
      
      setLoading(true)
      try {
        // 서버 액션 호출
        const metaData = await fetchFormMetadata(form.formCode, form.projectId)
        if (metaData) {
          setMetadata(metaData)
        } else {
          setMetadata(null)
        }
      } catch (error) {
        console.error("Error fetching form metadata:", error)
        setMetadata(null)
      } finally {
        setLoading(false)
      }
    }
    
    fetchMeta()
  }, [form, open])

  if (!form) return null

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="sm:max-w-xl md:max-w-3xl lg:max-w-4xl xl:max-w-5xl overflow-y-auto">

          <SheetHeader className="mb-4">
            <SheetTitle>Form Metadata</SheetTitle>
            <SheetDescription>
            </SheetDescription>
              {loading ? (
                <div className="text-muted-foreground">Loading metadata...</div>
              ) : metadata ? (
                <div className="flex flex-col gap-1">
                  <div className="flex gap-2 items-center">
                    <span className="font-semibold">Form Code:</span>
                    <Badge variant="outline">{metadata.formCode}</Badge>
                  </div>
                  <div className="flex gap-2 items-center">
                    <span className="font-semibold">Form Name:</span>
                    <span>{metadata.formName}</span>
                  </div>
                </div>
              ) : (
                <div className="text-sm text-muted-foreground">
                  No metadata found for form code: {form.formCode}
                </div>
              )}

          </SheetHeader>

          {loading ? (
            <div className="flex items-center justify-center h-40">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
          ) : metadata ? (
            <Tabs defaultValue="all" className="mt-4">
              <TabsList className="mb-4 flex-wrap">
                <TabsTrigger value="all">All ({metadata.columns.length})</TabsTrigger>
                {columnTypes.map((type) => (
                  <TabsTrigger key={type} value={type}>
                    {type} ({groupedColumns[type].length})
                  </TabsTrigger>
                ))}
              </TabsList>

              <TabsContent value="all">
                <Card>
                  <CardHeader>
                    <CardTitle>All Fields</CardTitle>
                    <CardDescription>All form fields and their properties</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Key</TableHead>
                          <TableHead>Label</TableHead>
                          <TableHead>Type</TableHead>
                          <TableHead>Options</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {metadata.columns.map((column) => (
                          <TableRow key={column.key}>
                            <TableCell className="font-mono text-sm">{column.key}</TableCell>
                            <TableCell>{column.label}</TableCell>
                            <TableCell>
                              <Badge variant="secondary">{column.type}</Badge>
                            </TableCell>
                            <TableCell>
                              <CollapsibleOptions options={column.options} />
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </CardContent>
                </Card>
              </TabsContent>

              {columnTypes.map((type) => (
                <TabsContent key={type} value={type}>
                  <Card>
                    <CardHeader>
                      <CardTitle>{type.charAt(0).toUpperCase() + type.slice(1)} Fields</CardTitle>
                      <CardDescription>Fields with type "{type}"</CardDescription>
                    </CardHeader>
                    <CardContent>
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Key</TableHead>
                            <TableHead>Label</TableHead>
                            {type === "LIST" && <TableHead>Options</TableHead>}
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {groupedColumns[type].map((column) => (
                            <TableRow key={column.key}>
                              <TableCell className="font-mono text-sm">{column.key}</TableCell>
                              <TableCell>{column.label}</TableCell>
                              {type === "LIST" && (
                                <TableCell>
                                  <CollapsibleOptions options={column.options} />
                                </TableCell>
                              )}
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </CardContent>
                  </Card>
                </TabsContent>
              ))}
            </Tabs>
          ) : (
            <div className="text-center py-8">
              <div className="text-lg font-medium">No metadata found</div>
              <p className="text-muted-foreground mt-2">
                Could not find metadata for form code: {form.formCode}
              </p>
            </div>
          )}
    
      </SheetContent>
    </Sheet>
  )
}