"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"
import { createApprovalLine } from "../service"
import { type ApprovalLineFormData, ApprovalLineSchema } from "../validations"
import { ApprovalLineSelector } from "@/components/knox/approval/ApprovalLineSelector"
import { OrganizationManagerSelector, type OrganizationManagerItem } from "@/components/common/organization/organization-manager-selector"
import { useSession } from "next-auth/react"
import { getActiveApprovalTemplateCategories, type ApprovalTemplateCategory } from "@/lib/approval-template/category-service"

interface CreateApprovalLineSheetProps {
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function CreateApprovalLineSheet({ open, onOpenChange }: CreateApprovalLineSheetProps) {
  const { data: session } = useSession();
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [categories, setCategories] = React.useState<ApprovalTemplateCategory[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = React.useState(false);

  // 고유 ID 생성 함수 (조직 관리자 추가 시 사용)
  const generateUniqueId = () => `apln-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;

  const form = useForm<ApprovalLineFormData>({
    resolver: zodResolver(ApprovalLineSchema),
    defaultValues: {
      name: "",
      category: "",
      description: "",
      aplns: [
        // 기안자는 항상 첫 번째로 고정 (플레이스홀더)
        {
          id: generateUniqueId(),
          epId: undefined,
          userId: undefined,
          emailAddress: undefined,
          name: "기안자",
          deptName: undefined,
          role: "0",
          seq: "0",
          opinion: "",
        },
      ],
    },
  });

  const aplns = form.watch("aplns");

  // 카테고리 목록 로드
  React.useEffect(() => {
    let active = true;
    const loadCategories = async () => {
      if (!open) return;

      setIsLoadingCategories(true);
      try {
        const data = await getActiveApprovalTemplateCategories();
        if (active) {
          setCategories(data);
        }
      } catch (error) {
        console.error('카테고리 로드 실패:', error);
      } finally {
        if (active) setIsLoadingCategories(false);
      }
    };
    loadCategories();
    return () => {
      active = false;
    };
  }, [open]);

  // 조직 관리자 추가 (공용 선택기 외 보조 입력 경로)
  const addOrganizationManagers = (managers: OrganizationManagerItem[]) => {
    const next = [...aplns];
    const uniqueSeqs = Array.from(new Set(next.map((a) => parseInt(a.seq))));
    const maxSeq = uniqueSeqs.length ? Math.max(...uniqueSeqs) : 0;

    managers.forEach((manager, idx) => {
      const exists = next.findIndex((a) => a.epId === manager.managerId);
      if (exists === -1) {
        const newSeqNum = Math.max(1, maxSeq + 1 + idx);
        const newSeq = newSeqNum.toString();
        next.push({
          id: generateUniqueId(),
          epId: manager.managerId,
          userId: undefined,
          emailAddress: undefined,
          name: manager.managerName,
          deptName: manager.departmentName,
          role: "1",
          seq: newSeq,
          opinion: "",
        });
      }
    });

    form.setValue("aplns", next, { shouldDirty: true });
  };

  const onSubmit = async (data: ApprovalLineFormData) => {
    setIsSubmitting(true);
    try {
      if (!session?.user?.id) {
        toast.error("로그인이 필요합니다.");
        return;
      }

      await createApprovalLine({
        name: data.name,
        category: data.category || undefined,
        description: data.description,
        aplns: data.aplns,
        createdBy: Number(session.user.id),
      });

      toast.success("결재선이 성공적으로 생성되었습니다.");
      form.reset();
      onOpenChange(false);
    } catch {
      toast.error("결재선 생성 중 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full sm:max-w-4xl overflow-y-auto">
        <SheetHeader>
          <SheetTitle>결재선 생성</SheetTitle>
          <SheetDescription>
            새로운 결재선을 생성합니다. 결재자를 추가하고 순서를 조정할 수 있습니다.
          </SheetDescription>
        </SheetHeader>

        <div className="mt-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {/* 기본 정보 */}
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>결재선 이름 *</FormLabel>
                      <FormControl>
                        <Input placeholder="결재선 이름을 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>카테고리</FormLabel>
                      <Select
                        value={field.value || "none"}
                        onValueChange={(value) => field.onChange(value === "none" ? "" : value)}
                        disabled={isLoadingCategories}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder={isLoadingCategories ? "카테고리 로드 중..." : "카테고리를 선택하세요"} />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">선택 안함</SelectItem>
                          {categories
                            .sort((a, b) => a.sortOrder - b.sortOrder)
                            .map((category) => (
                              <SelectItem key={`category-${category.id}`} value={category.name}>
                                {category.name}
                                {category.description && (
                                  <span className="text-muted-foreground ml-2">({category.description})</span>
                                )}
                              </SelectItem>
                            ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>설명</FormLabel>
                      <FormControl>
                        <Textarea placeholder="결재선에 대한 설명을 입력하세요" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <Separator />

              {/* 결재 경로 */}
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">결재 경로</h3>

                <ApprovalLineSelector
                  value={aplns}
                  onChange={(next) => form.setValue("aplns", next, { shouldDirty: true })}
                  placeholder="결재자를 검색하세요..."
                  domainFilter={{ type: "exclude", domains: ["partners"] }}
                  maxSelections={10}
                />

                {/* 조직 관리자 추가 (선택 사항) */}
                {/* <div className="p-4 border border-dashed border-gray-300 rounded-lg">
                  <div className="mb-2">
                    <label className="text-sm font-medium text-gray-700">조직 관리자로 추가</label>
                    <p className="text-xs text-gray-500">조직별 책임자를 검색하여 추가하세요</p>
                  </div>
                  <OrganizationManagerSelector
                    selectedManagers={[]}
                    onManagersChange={addOrganizationManagers}
                    placeholder="조직 관리자를 검색하세요..."
                    maxSelections={10}
                  />
                </div> */}
              </div>

              <Separator />

              {/* 제출 버튼 */}
              <div className="flex justify-end space-x-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => onOpenChange(false)}
                  disabled={isSubmitting}
                >
                  취소
                </Button>
                <Button type="submit" disabled={isSubmitting}>
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      생성 중...
                    </>
                  ) : (
                    "결재선 생성"
                  )}
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </SheetContent>
    </Sheet>
  )
} 