"use client";

import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { complianceSurveyTemplates } from "@/db/schema/compliance";
import { updateComplianceSurveyTemplate } from "@/lib/compliance/services";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

const templateSchema = z.object({
  name: z.string().min(1, "템플릿명을 입력하세요"),
  description: z.string().min(1, "설명을 입력하세요"),
  version: z.string().min(1, "버전을 입력하세요"),
  isActive: z.boolean(),
});

type TemplateFormData = z.infer<typeof templateSchema>;

interface ComplianceTemplateEditSheetProps {
  template: typeof complianceSurveyTemplates.$inferSelect;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ComplianceTemplateEditSheet({ 
  template, 
  open, 
  onOpenChange
}: ComplianceTemplateEditSheetProps) {
  const [isLoading, setIsLoading] = React.useState(false);
  const router = useRouter();

  const form = useForm<TemplateFormData>({
    resolver: zodResolver(templateSchema),
    defaultValues: {
      name: template.name,
      description: template.description,
      version: template.version,
      isActive: template.isActive,
    },
  });

  const onSubmit = async (data: TemplateFormData) => {
    try {
      setIsLoading(true);
      
      await updateComplianceSurveyTemplate(template.id, data);

      toast.success("템플릿이 성공적으로 수정되었습니다.");
      onOpenChange(false);
      
      // 페이지 새로고침
      router.refresh();
    } catch (error) {
      console.error("Error updating template:", error);
      toast.error("템플릿 수정 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent>
        <SheetHeader>
          <SheetTitle>템플릿 수정</SheetTitle>
          <SheetDescription>
            템플릿 정보를 수정합니다.
          </SheetDescription>
        </SheetHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} 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="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>설명</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="템플릿 설명을 입력하세요" 
                      className="min-h-[100px]"
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="version"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>버전</FormLabel>
                  <FormControl>
                    <Input placeholder="버전을 입력하세요" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="isActive"
              render={({ field }) => (
                <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                  <FormControl>
                    <Checkbox
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                  <div className="space-y-1 leading-none">
                    <FormLabel>활성 상태</FormLabel>
                    <FormDescription>
                      템플릿을 활성화하여 사용할 수 있도록 설정
                    </FormDescription>
                  </div>
                </FormItem>
              )}
            />

            <SheetFooter>
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => onOpenChange(false)}
                disabled={isLoading}
              >
                취소
              </Button>
              <Button type="submit" disabled={isLoading}>
                {isLoading ? "수정 중..." : "템플릿 수정"}
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  );
}
