"use client"

import { useState, useEffect, useTransition } from "react"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { 
  Search, 
  Edit, 
  FileText, 
  ChevronUp, 
  ChevronDown, 
  Plus,
  Eye,
  Trash2
} from "lucide-react"
import { toast } from "sonner"
import { formatDate } from "@/lib/utils"
import { getNoticeLists, deleteNotice, getPagePathList } from "@/lib/notice/service"
import type { Notice } from "@/db/schema/notice"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { UpdateNoticeSheet } from "./notice-edit-sheet"
import { NoticeCreateDialog } from "./notice-create-dialog"
import { NoticeViewDialog } from "./notice-view-dialog"

type NoticeWithAuthor = Notice & {
  authorName: string | null
  authorEmail: string | null
}

interface NoticeClientProps {
  initialData?: NoticeWithAuthor[]
  currentUserId?: number
}

type SortField = "title" | "pagePath" | "createdAt"
type SortDirection = "asc" | "desc"

export function NoticeClient({ initialData = [], currentUserId }: NoticeClientProps) {
  const params = useParams()
  const lng = (params?.lng as string) || 'ko'
  const { t } = useTranslation(lng, 'menu')
  
  // 안전한 번역 함수 (키가 없을 때 원본 키 반환)
  const safeTranslate = (key: string): string => {
    try {
      const translated = t(key)
      // 번역 키가 그대로 반환되는 경우 원본 키 사용
      if (translated === key) {
        return key
      }
      return translated || key
    } catch (error) {
      console.warn(`Translation failed for key: ${key}`, error)
      return key
    }
  }
  
  const [notices, setNotices] = useState<NoticeWithAuthor[]>(initialData)
  const [loading, setLoading] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [sortField, setSortField] = useState<SortField>("createdAt")
  const [sortDirection, setSortDirection] = useState<SortDirection>("desc")
  const [, startTransition] = useTransition()
  const [isEditSheetOpen, setIsEditSheetOpen] = useState(false)
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false)
  const [selectedNotice, setSelectedNotice] = useState<NoticeWithAuthor | null>(null)
  const [pagePathOptions, setPagePathOptions] = useState<Array<{ value: string; label: string }>>([])
  // 공지사항 목록 조회
  const fetchNotices = async () => {
    try {
      setLoading(true)
      const search = searchQuery || undefined

      startTransition(async () => {
        const result = await getNoticeLists({
          page: 1,
          perPage: 50,
          search: search,
          sort: [{ id: sortField, desc: sortDirection === "desc" }],
          flags: [],
          filters: [],
          joinOperator: "and",
          pagePath: "",
          title: "",
          content: "",
          authorId: null,
          isActive: null,
          from: "",
          to: "",
        })

        if (result?.data) {
          setNotices(result.data)
        } else {
          toast.error("공지사항 목록을 가져오는데 실패했습니다.")
        }
        setLoading(false)
      })
    } catch (error) {
      console.error("Error fetching notices:", error)
      toast.error("공지사항 목록을 가져오는데 실패했습니다.")
      setLoading(false)
    }
  }

  // 검색 핸들러
  const handleSearch = () => {
    fetchNotices()
  }

  // 정렬 함수
  const sortNotices = (notices: NoticeWithAuthor[]) => {
    return [...notices].sort((a, b) => {
      let aValue: string | Date
      let bValue: string | Date

      if (sortField === "title") {
        aValue = a.title
        bValue = b.title
      } else if (sortField === "pagePath") {
        aValue = a.pagePath
        bValue = b.pagePath
      } else {
        aValue = new Date(a.createdAt)
        bValue = new Date(b.createdAt)
      }

      if (aValue < bValue) {
        return sortDirection === "asc" ? -1 : 1
      }
      if (aValue > bValue) {
        return sortDirection === "asc" ? 1 : -1
      }
      return 0
    })
  }

  // 정렬 핸들러
  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc")
    } else {
      setSortField(field)
      setSortDirection("asc")
    }
  }

  // 삭제 핸들러
  const handleDelete = async (notice: NoticeWithAuthor) => {
    try {
      const result = await deleteNotice(notice.id)
      
      if (result.success) {
        toast.success(result.message)
        setNotices(notices.filter(n => n.id !== notice.id))
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error("Error deleting notice:", error)
      toast.error("공지사항 삭제에 실패했습니다.")
    }
  }

  // 정렬된 공지사항 목록
  const sortedNotices = sortNotices(notices)

  // 페이지 경로 옵션 로딩
  const loadPagePathOptions = async () => {
    try {
      const paths = await getPagePathList()
      const options = paths.map(path => ({
        value: path.pagePath,
        label: path.pageName // i18n 키를 그대로 저장 (화면에서 번역)
      }))
      setPagePathOptions(options)
    } catch (error) {
      console.error("페이지 경로 로딩 실패:", error)
    }
  }

  // View 다이얼로그 열기
  const handleViewNotice = (notice: NoticeWithAuthor) => {
    setSelectedNotice(notice)
    setIsViewDialogOpen(true)
  }

  // Edit Sheet 열기
  const handleEditNotice = (notice: NoticeWithAuthor) => {
    setSelectedNotice(notice)
    setIsEditSheetOpen(true)
  }

  // Create Dialog 열기
  const handleCreateNotice = () => {
    setIsCreateDialogOpen(true)
  }

  useEffect(() => {
    if (initialData.length > 0) {
      setNotices(initialData)
    } else {
      fetchNotices()
    }
    loadPagePathOptions()
  }, [])

  useEffect(() => {
    if (searchQuery !== "") {
      fetchNotices()
    } else if (initialData.length > 0) {
      setNotices(initialData)
    }
  }, [searchQuery])

  return (
    <div className="space-y-6">
      {/* 검색 및 추가 버튼 */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
            <Input
              placeholder="제목이나 페이지 경로로 검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10"
              onKeyPress={(e) => e.key === "Enter" && handleSearch()}
            />
          </div>
          <Button onClick={handleSearch} variant="outline">
            검색
          </Button>
          <Button
            variant="outline"
            onClick={() => window.location.reload()}
          >
            새로고침
          </Button>
        </div>
        <Button onClick={handleCreateNotice}>
          <Plus className="h-4 w-4 mr-2" />
          공지사항 추가
        </Button>
      </div>

      {/* 공지사항 테이블 */}
      <div className="bg-white rounded-lg shadow">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("title")}
                >
                  제목
                  {sortField === "title" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("pagePath")}
                >
                  페이지 경로
                  {sortField === "pagePath" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead>작성자</TableHead>
              <TableHead>상태</TableHead>
              <TableHead>
                <button
                  className="flex items-center gap-1 hover:text-foreground"
                  onClick={() => handleSort("createdAt")}
                >
                  생성일
                  {sortField === "createdAt" && (
                    sortDirection === "asc" ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )
                  )}
                </button>
              </TableHead>
              <TableHead className="text-right">작업</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8">
                  로딩 중...
                </TableCell>
              </TableRow>
            ) : notices.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-gray-500">
                  공지사항이 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              sortedNotices.map((notice) => (
                <TableRow key={notice.id}>
                  <TableCell className="font-medium">
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4" />
                      <span className="max-w-[300px] truncate">
                        {notice.title}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="max-w-[200px]">
                      <div className="font-mono text-xs text-muted-foreground truncate">
                        {notice.pagePath}
                      </div>
                      <div className="text-sm truncate">
                        {(() => {
                          const pageOption = pagePathOptions.find(opt => opt.value === notice.pagePath)
                          return pageOption ? safeTranslate(pageOption.label) : notice.pagePath
                        })()}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-col">
                      <span className="font-medium text-sm">
                        {notice.authorName || "알 수 없음"}
                      </span>
                      {notice.authorEmail && (
                        <span className="text-xs text-muted-foreground">
                          {notice.authorEmail}
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant={notice.isActive ? "default" : "secondary"}>
                      {notice.isActive ? "활성" : "비활성"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {formatDate(notice.createdAt, "KR")}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-2">
                      {/* View 버튼 - 다이얼로그 방식 */}
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => handleViewNotice(notice)}
                        title="공지사항 보기 (Dialog)"
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      
                      {/* Edit 버튼 - 다이얼로그 방식 */}
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => handleEditNotice(notice)}
                        title="공지사항 편집 (Dialog)"
                      >
                        <Edit className="h-4 w-4" />
                      </Button>

                      {/* 기존 페이지 방식 (비교용)
                      <Link href={`/${lng}/evcp/notice/${notice.id}/view`}>
                        <Button variant="outline" size="sm" title="공지사항 보기 (Page)">
                          <FileText className="h-4 w-4" />
                        </Button>
                      </Link> */}
                      
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button variant="outline" size="sm" className="text-red-600 hover:text-red-700">
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>공지사항 삭제</AlertDialogTitle>
                            <AlertDialogDescription>
                              이 공지사항을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>취소</AlertDialogCancel>
                            <AlertDialogAction 
                              onClick={() => handleDelete(notice)}
                              className="bg-red-600 hover:bg-red-700"
                            >
                              삭제
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 다이얼로그들과 시트 - 테이블 밖에서 단일 렌더링 */}
      <NoticeViewDialog
        open={isViewDialogOpen}
        onOpenChange={setIsViewDialogOpen}
        notice={selectedNotice}
      />

      <NoticeCreateDialog
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        pagePathOptions={pagePathOptions}
        currentUserId={currentUserId}
        onSuccess={fetchNotices}
      />

      <UpdateNoticeSheet
        open={isEditSheetOpen}
        onOpenChange={setIsEditSheetOpen}
        notice={selectedNotice}
        pagePathOptions={pagePathOptions}
        onSuccess={fetchNotices}
      />
    </div>
  )
} 