"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Switch } from "@/components/ui/switch"

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import { Loader, Edit, AlertCircle } from "lucide-react"
import { toast } from "sonner"

import { bulkUpdateGtcClausesSchema, type BulkUpdateGtcClausesSchema } from "@/lib/gtc-contract/gtc-clauses/validations"
import { bulkUpdateGtcClauses } from "@/lib/gtc-contract/gtc-clauses/service"
import { type GtcClauseTreeView } from "@/db/schema/gtc"
import { useSession } from "next-auth/react"

interface BulkUpdateGtcClausesDialogProps
  extends React.ComponentPropsWithRef<typeof Dialog> {
  selectedClauses: GtcClauseTreeView[]
}

export function BulkUpdateGtcClausesDialog({ 
  selectedClauses, 
  ...props 
}: BulkUpdateGtcClausesDialogProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const { data: session } = useSession()

  const currentUserId = React.useMemo(() => {
    return session?.user?.id ? Number(session.user.id) : null
  }, [session])

  const form = useForm<BulkUpdateGtcClausesSchema>({
    resolver: zodResolver(bulkUpdateGtcClausesSchema),
    defaultValues: {
      clauseIds: selectedClauses.map(clause => clause.id),
      updates: {
        category: "",
        isActive: true,
      },
      editReason: "",
    },
  })

  React.useEffect(() => {
    if (selectedClauses.length > 0) {
      form.setValue("clauseIds", selectedClauses.map(clause => clause.id))
    }
  }, [selectedClauses, form])

  async function onSubmit(data: BulkUpdateGtcClausesSchema) {
    startUpdateTransition(async () => {
      if (!currentUserId) {
        toast.error("로그인이 필요합니다")
        return
      }

      try {
        const result = await bulkUpdateGtcClauses({
          ...data,
          updatedById: currentUserId
        })
        
        if (result.error) {
          toast.error(`에러: ${result.error}`)
          return
        }

        form.reset()
        props.onOpenChange?.(false)
        toast.success(`${selectedClauses.length}개의 조항이 수정되었습니다.`)
      } catch (error) {
        toast.error("조항 일괄 수정 중 오류가 발생했습니다.")
      }
    })
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    if (!nextOpen) {
      form.reset()
    }
    props.onOpenChange?.(nextOpen)
  }

  // 선택된 조항들의 통계
  const categoryCounts = React.useMemo(() => {
    const counts: Record<string, number> = {}
    selectedClauses.forEach(clause => {
      const category = clause.category || "미분류"
      counts[category] = (counts[category] || 0) + 1
    })
    return counts
  }, [selectedClauses])

  const activeCount = selectedClauses.filter(clause => clause.isActive).length
  const inactiveCount = selectedClauses.length - activeCount

  if (selectedClauses.length === 0) {
    return null
  }

  return (
    <Dialog {...props} onOpenChange={handleDialogOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Edit className="h-5 w-5" />
            조항 일괄 수정
          </DialogTitle>
          <DialogDescription>
            선택한 {selectedClauses.length}개 조항의 공통 속성을 일괄 수정합니다.
          </DialogDescription>
        </DialogHeader>

        {/* 선택된 조항 요약 */}
        <div className="space-y-4 p-4 bg-muted/50 rounded-lg">
          <div className="flex items-center gap-2">
            <AlertCircle className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">선택된 조항 정보</span>
          </div>
          
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <div className="font-medium text-muted-foreground mb-1">총 조항 수</div>
              <div>{selectedClauses.length}개</div>
            </div>
            
            <div>
              <div className="font-medium text-muted-foreground mb-1">상태</div>
              <div className="flex gap-2">
                <Badge variant="default">{activeCount}개 활성</Badge>
                {inactiveCount > 0 && (
                  <Badge variant="secondary">{inactiveCount}개 비활성</Badge>
                )}
              </div>
            </div>
          </div>

          {/* 분류별 통계 */}
          <div>
            <div className="font-medium text-muted-foreground mb-2">현재 분류 현황</div>
            <div className="flex flex-wrap gap-1">
              {Object.entries(categoryCounts).map(([category, count]) => (
                <Badge key={category} variant="outline" className="text-xs">
                  {category}: {count}개
                </Badge>
              ))}
            </div>
          </div>

          {/* 조항 미리보기 (최대 5개) */}
          <div>
            <div className="font-medium text-muted-foreground mb-2">포함된 조항 (일부)</div>
            <div className="space-y-1 max-h-24 overflow-y-auto">
              {selectedClauses.slice(0, 5).map(clause => (
                <div key={clause.id} className="flex items-center gap-2 text-xs">
                  <Badge variant="outline">{clause.itemNumber}</Badge>
                  <span className="truncate">{clause.subtitle}</span>
                </div>
              ))}
              {selectedClauses.length > 5 && (
                <div className="text-xs text-muted-foreground">
                  ... 외 {selectedClauses.length - 5}개 조항
                </div>
              )}
            </div>
          </div>
        </div>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="space-y-4">
              {/* 분류 수정 */}
              <FormField
                control={form.control}
                name="updates.category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>분류 변경 (선택사항)</FormLabel>
                    <FormControl>
                      <Input 
                        placeholder="새로운 분류명을 입력하세요 (빈칸으로 두면 변경하지 않음)"
                        {...field} 
                      />
                    </FormControl>
                    <FormDescription>
                      모든 선택된 조항의 분류가 동일한 값으로 변경됩니다.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* 활성 상태 변경 */}
              <FormField
                control={form.control}
                name="updates.isActive"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                    <div className="space-y-0.5">
                      <FormLabel className="text-base">활성 상태</FormLabel>
                      <FormDescription>
                        선택된 모든 조항의 활성 상태를 설정합니다.
                      </FormDescription>
                    </div>
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                  </FormItem>
                )}
              />

              {/* 편집 사유 */}
              <FormField
                control={form.control}
                name="editReason"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>편집 사유 *</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="일괄 수정 사유를 입력하세요..."
                        {...field}
                        rows={3}
                      />
                    </FormControl>
                    <FormDescription>
                      일괄 수정의 이유를 명확히 기록해주세요.
                    </FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <DialogFooter className="mt-6">
              <Button
                type="button"
                variant="outline"
                onClick={() => props.onOpenChange?.(false)}
                disabled={isUpdatePending}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={isUpdatePending}>
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                Update {selectedClauses.length} Clauses
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}