"use client";

import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
import { BatchAPI, BatchJob } from "@/lib/api/batch";
// import { CollectionAPI } from "@/lib/api/collection"; // 사용하지 않는 import 제거

interface BatchJobModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => void;
  job?: BatchJob | null;
}

export default function BatchJobModal({
  isOpen,
  onClose,
  onSave,
  job,
}: BatchJobModalProps) {
  const [formData, setFormData] = useState<Partial<BatchJob>>({
    job_name: "",
    description: "",
    job_type: "collection",
    schedule_cron: "",
    is_active: "Y",
    config_json: {},
    execution_count: 0,
    success_count: 0,
    failure_count: 0,
  });
  const [isLoading, setIsLoading] = useState(false);
  const [jobTypes, setJobTypes] = useState<Array<{ value: string; label: string }>>([]);
  const [schedulePresets, setSchedulePresets] = useState<Array<{ value: string; label: string }>>([]);
  const [collectionConfigs, setCollectionConfigs] = useState<any[]>([]);

  useEffect(() => {
    if (isOpen) {
      loadJobTypes();
      loadSchedulePresets();
      loadCollectionConfigs();
      
      if (job) {
        setFormData({
          ...job,
          config_json: job.config_json || {},
        });
      } else {
        setFormData({
          job_name: "",
          description: "",
          job_type: "collection",
          schedule_cron: "",
          is_active: "Y",
          config_json: {},
          execution_count: 0,
          success_count: 0,
          failure_count: 0,
        });
      }
    }
  }, [isOpen, job]);

  const loadJobTypes = async () => {
    try {
      const types = await BatchAPI.getSupportedJobTypes();
      setJobTypes(types);
    } catch (error) {
      console.error("작업 타입 조회 오류:", error);
    }
  };

  const loadSchedulePresets = async () => {
    try {
      const presets = await BatchAPI.getSchedulePresets();
      setSchedulePresets(presets);
    } catch (error) {
      console.error("스케줄 프리셋 조회 오류:", error);
    }
  };

  const loadCollectionConfigs = async () => {
    try {
      // 배치 설정 조회로 대체
      const configs = await BatchAPI.getBatchConfigs({
        is_active: "Y",
      });
      setCollectionConfigs(configs.data || []);
    } catch (error) {
      console.error("배치 설정 조회 오류:", error);
      setCollectionConfigs([]);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.job_name || !formData.job_type) {
      toast.error("필수 필드를 모두 입력해주세요.");
      return;
    }

    setIsLoading(true);
    try {
      if (job?.id) {
        await BatchAPI.updateBatchJob(job.id, formData);
        toast.success("배치 작업이 수정되었습니다.");
      } else {
        await BatchAPI.createBatchJob(formData as BatchJob);
        toast.success("배치 작업이 생성되었습니다.");
      }
      onSave();
      onClose();
    } catch (error) {
      console.error("배치 작업 저장 오류:", error);
      toast.error(
        error instanceof Error ? error.message : "배치 작업 저장에 실패했습니다."
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleSchedulePresetSelect = (preset: string) => {
    setFormData(prev => ({
      ...prev,
      schedule_cron: preset,
    }));
  };

  const handleJobTypeChange = (jobType: string) => {
    setFormData(prev => ({
      ...prev,
      job_type: jobType as any,
      config_json: {},
    }));
  };

  const handleCollectionConfigChange = (configId: string) => {
    setFormData(prev => ({
      ...prev,
      config_json: {
        ...prev.config_json,
        collectionConfigId: parseInt(configId),
      },
    }));
  };

  const getJobTypeIcon = (type: string) => {
    switch (type) {
      case 'collection': return '📥';
      case 'sync': return '🔄';
      case 'cleanup': return '🧹';
      case 'custom': return '⚙️';
      default: return '📋';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'Y': return 'bg-green-100 text-green-800';
      case 'N': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {job ? "배치 작업 수정" : "새 배치 작업"}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 기본 정보 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">기본 정보</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="job_name">작업명 *</Label>
                <Input
                  id="job_name"
                  value={formData.job_name || ""}
                  onChange={(e) =>
                    setFormData(prev => ({ ...prev, job_name: e.target.value }))
                  }
                  placeholder="배치 작업명을 입력하세요"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="job_type">작업 타입 *</Label>
                <Select
                  value={formData.job_type || "collection"}
                  onValueChange={handleJobTypeChange}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {jobTypes.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        <span className="flex items-center gap-2">
                          <span>{getJobTypeIcon(type.value)}</span>
                          {type.label}
                        </span>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="description">설명</Label>
              <Textarea
                id="description"
                value={formData.description || ""}
                onChange={(e) =>
                  setFormData(prev => ({ ...prev, description: e.target.value }))
                }
                placeholder="배치 작업에 대한 설명을 입력하세요"
                rows={3}
              />
            </div>
          </div>

          {/* 작업 설정 */}
          {formData.job_type === 'collection' && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium">수집 설정</h3>
              
              <div className="space-y-2">
                <Label htmlFor="collection_config">수집 설정</Label>
                <Select
                  value={formData.config_json?.collectionConfigId?.toString() || ""}
                  onValueChange={handleCollectionConfigChange}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="수집 설정을 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    {collectionConfigs.map((config) => (
                      <SelectItem key={config.id} value={config.id.toString()}>
                        {config.config_name} - {config.source_table}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          )}

          {/* 스케줄 설정 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">스케줄 설정</h3>
            
            <div className="space-y-2">
              <Label htmlFor="schedule_cron">Cron 표현식</Label>
              <div className="flex gap-2">
                <Input
                  id="schedule_cron"
                  value={formData.schedule_cron || ""}
                  onChange={(e) =>
                    setFormData(prev => ({ ...prev, schedule_cron: e.target.value }))
                  }
                  placeholder="예: 0 0 * * * (매일 자정)"
                  className="flex-1"
                />
                <Select onValueChange={handleSchedulePresetSelect}>
                  <SelectTrigger className="w-32">
                    <SelectValue placeholder="프리셋" />
                  </SelectTrigger>
                  <SelectContent>
                    {schedulePresets.map((preset) => (
                      <SelectItem key={preset.value} value={preset.value}>
                        {preset.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>

          {/* 실행 통계 (수정 모드일 때만) */}
          {job?.id && (
            <div className="space-y-4">
              <h3 className="text-lg font-medium">실행 통계</h3>
              
              <div className="grid grid-cols-3 gap-4">
                <div className="p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">
                    {formData.execution_count || 0}
                  </div>
                  <div className="text-sm text-gray-600">총 실행 횟수</div>
                </div>
                
                <div className="p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-green-600">
                    {formData.success_count || 0}
                  </div>
                  <div className="text-sm text-gray-600">성공 횟수</div>
                </div>
                
                <div className="p-4 border rounded-lg">
                  <div className="text-2xl font-bold text-red-600">
                    {formData.failure_count || 0}
                  </div>
                  <div className="text-sm text-gray-600">실패 횟수</div>
                </div>
              </div>

              {formData.last_executed_at && (
                <div className="text-sm text-gray-600">
                  마지막 실행: {new Date(formData.last_executed_at).toLocaleString()}
                </div>
              )}
            </div>
          )}

          {/* 활성화 설정 */}
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Switch
                id="is_active"
                checked={formData.is_active === "Y"}
                onCheckedChange={(checked) =>
                  setFormData(prev => ({ ...prev, is_active: checked ? "Y" : "N" }))
                }
              />
              <Label htmlFor="is_active">활성화</Label>
            </div>
            
            <Badge className={getStatusColor(formData.is_active || "N")}>
              {formData.is_active === "Y" ? "활성" : "비활성"}
            </Badge>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              취소
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? "저장 중..." : "저장"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
