"use client"

import * as React from "react"
import { toast } from "sonner"
import { Loader, Save, ArrowLeft, Eye } from "lucide-react"
import Link from "next/link"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { formatApprovalLine } from "@/lib/approval-line/utils/format"
import { getApprovalLineOptionsAction } from "@/lib/approval-line/service"

import { type ApprovalTemplate } from "@/lib/approval-template/service"
import { updateApprovalTemplateAction } from "@/lib/approval-template/service"
import { getActiveApprovalTemplateCategories, type ApprovalTemplateCategory } from "@/lib/approval-template/category-service"
import { useSession } from "next-auth/react"
import { useRouter, usePathname } from "next/navigation"

interface ApprovalTemplateEditorProps {
  templateId: string
  initialTemplate: ApprovalTemplate
  approvalLineOptions: Array<{ id: string; name: string }>
}

export function ApprovalTemplateEditor({ templateId, initialTemplate, approvalLineOptions }: ApprovalTemplateEditorProps) {
  const { data: session } = useSession()
  const router = useRouter()
  const pathname = usePathname()
  const [template, setTemplate] = React.useState(initialTemplate)
  const [isSaving, startSaving] = React.useTransition()
  const [htmlContent, setHtmlContent] = React.useState(initialTemplate.content)
  const [previewKey, setPreviewKey] = React.useState(0) // 미리보기 업데이트용

  const [form, setForm] = React.useState({
    name: template.name,
    subject: template.subject,
    description: template.description ?? "",
    category: template.category ?? "",
    approvalLineId: (template as { approvalLineId?: string | null }).approvalLineId ?? "",
  })

  const [categories, setCategories] = React.useState<ApprovalTemplateCategory[]>([])
  const [isLoadingCategories, setIsLoadingCategories] = React.useState(false)
  const [category, setCategory] = React.useState(form.category ?? "")
  const [isInitialLoad, setIsInitialLoad] = React.useState(true)
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [lineOptions, setLineOptions] = React.useState(approvalLineOptions as Array<{ id: string; name: string; aplns?: any[]; category?: string | null }>)
  const [isLoadingLines, setIsLoadingLines] = React.useState(false)

  // 카테고리 목록 로드 (초기 한 번만)
  React.useEffect(() => {
    let active = true
    const loadCategories = async () => {
      setIsLoadingCategories(true)
      try {
        const data = await getActiveApprovalTemplateCategories()
        if (active) {
          setCategories(data)
          // 초기 로드 시에만 기본 카테고리 설정 (템플릿의 카테고리가 없고 카테고리가 선택되지 않은 경우)
          if (isInitialLoad && !category && data.length > 0) {
            const defaultCategory = form.category || data[0].name
            setCategory(defaultCategory)
          }
          setIsInitialLoad(false)
        }
      } catch (error) {
        console.error('카테고리 로드 실패:', error)
      } finally {
        if (active) setIsLoadingCategories(false)
      }
    }
    loadCategories()
    return () => {
      active = false
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []) // 빈 의존성 배열로 초기 한 번만 실행

  // 결재선 옵션 로드
  React.useEffect(() => {
    let active = true
    const run = async () => {
      setIsLoadingLines(true)
      const { success, data } = await getApprovalLineOptionsAction(category || undefined)
      if (active) {
        setIsLoadingLines(false)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        if (success && data) setLineOptions(data as any)
        // 카테고리 바뀌면 결재선 선택 초기화
        setForm((prev) => ({ ...prev, category, approvalLineId: "" }))
      }
    }
    run()
    return () => {
      active = false
    }
  }, [category])

  function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
    const { name, value } = e.target
    setForm((prev) => ({ ...prev, [name]: value }))
  }

  // 미리보기 새로고침
  function refreshPreview() {
    setPreviewKey((prev) => prev + 1)
    toast.success("미리보기를 업데이트했습니다")
  }

  function handleSave() {
    startSaving(async () => {
      if (!session?.user?.id) {
        toast.error("로그인이 필요합니다")
        return
      }

      const { success, error, data } = await updateApprovalTemplateAction(templateId, {
        name: form.name,
        subject: form.subject,
        content: htmlContent,
        description: form.description,
        category: form.category || undefined,
        approvalLineId: form.approvalLineId ? form.approvalLineId : null,
        updatedBy: Number(session.user.id),
      })

      if (!success || error || !data) {
        toast.error(error ?? "저장에 실패했습니다")
        return
      }

      setTemplate(data)
      toast.success("저장되었습니다")

      // 저장 후 목록 페이지로 이동 (back-button.tsx 로직 참고)
      if (pathname) {
        const segments = pathname.split('/').filter(Boolean)
        const newSegments = segments.slice(0, -1) // 마지막 세그먼트(ID) 제거
        const targetPath = newSegments.length > 0 ? `/${newSegments.join('/')}` : '/'
        router.push(targetPath)
      }
    })
  }

  return (
    <div className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" asChild>
          <Link href="/evcp/approval/template">
            <ArrowLeft className="h-4 w-4" />
          </Link>
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-semibold">{template.name}</h1>
            <Badge variant="outline" className="text-xs">
              최근 수정: {new Date(template.updatedAt).toLocaleDateString("ko-KR")}
            </Badge>
            {template.category && (
              <Badge variant="secondary" className="text-xs">{template.category}</Badge>
            )}
          </div>
          <p className="text-sm text-muted-foreground">{template.description || "결재 템플릿 편집"}</p>
        </div>
        <Button onClick={refreshPreview} variant="outline" size="sm">
          <Eye className="mr-2 h-4 w-4" /> 미리보기 새로고침
        </Button>
        <Button onClick={handleSave} disabled={isSaving}>
          {isSaving && <Loader className="mr-2 h-4 w-4 animate-spin" />}
          <Save className="mr-2 h-4 w-4" /> 저장
        </Button>
      </div>

      <Separator />

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">이름</label>
              <Input name="name" value={form.name} onChange={handleChange} />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium">카테고리</label>
              <Select
                value={category || "none"}
                onValueChange={(value) => setCategory(value === "none" ? "" : value)}
                disabled={isLoadingCategories}
              >
                <SelectTrigger>
                  <SelectValue placeholder={isLoadingCategories ? "카테고리 로드 중..." : "카테고리를 선택하세요"} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">선택 안함</SelectItem>
                  {categories
                    .sort((a, b) => a.sortOrder - b.sortOrder)
                    .map((cat) => (
                      <SelectItem key={`category-${cat.id}`} value={cat.name}>
                        {cat.name}
                        {cat.description && (
                          <span className="text-muted-foreground ml-2">({cat.description})</span>
                        )}
                      </SelectItem>
                    ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">설명 (선택)</label>
            <Input name="description" value={form.description} onChange={handleChange} />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">제목</label>
            <Input name="subject" value={form.subject} onChange={handleChange} />
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium">결재선</label>
            <Select
              value={form.approvalLineId}
              onValueChange={(value) => setForm((prev) => ({ ...prev, approvalLineId: value }))}
              disabled={!category || isLoadingLines}
            >
              <SelectTrigger>
                <SelectValue placeholder={category ? (isLoadingLines ? "불러오는 중..." : "결재선을 선택하세요") : "카테고리를 먼저 선택하세요"} />
              </SelectTrigger>
              <SelectContent>
                {lineOptions.map((opt) => {
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  const label = opt.aplns ? `${opt.name} — ${formatApprovalLine(opt.aplns as any)}` : opt.name
                  return (
                    <SelectItem key={opt.id} value={opt.id}>
                      {label}
                    </SelectItem>
                  )
                })}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* 2컬럼 레이아웃: 왼쪽 HTML 편집기, 오른쪽 미리보기 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 flex-1">
        {/* 왼쪽: HTML 편집기 */}
        <Card className="flex flex-col">
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>HTML 편집기</CardTitle>
                <CardDescription>HTML 코드를 직접 편집하세요</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="flex-1 flex flex-col">
            {/* HTML 입력 영역 */}
            <Textarea
              value={htmlContent}
              onChange={(e) => setHtmlContent(e.target.value)}
              className="font-mono text-sm flex-1 min-h-[600px] resize-none"
              placeholder="HTML 소스를 입력하세요..."
            />
          </CardContent>
        </Card>

        {/* 오른쪽: 미리보기 */}
        <Card className="flex flex-col">
          <CardHeader>
            <CardTitle>미리보기</CardTitle>
            <CardDescription>HTML이 실시간으로 렌더링됩니다</CardDescription>
          </CardHeader>
          <CardContent className="flex-1 overflow-auto">
            <div 
              key={previewKey}
              className="border rounded-md p-4 bg-background min-h-[600px]"
              dangerouslySetInnerHTML={{ __html: htmlContent }} 
            />
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
