"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { 
  Plus, 
  Search, 
  MoreHorizontal, 
  Edit, 
  Trash2, 
  Play, 
  RefreshCw,
  BarChart3,
  ArrowRight,
  Database,
  Globe
} from "lucide-react";
import { toast } from "sonner";
import { BatchAPI, BatchJob } from "@/lib/api/batch";
import BatchJobModal from "@/components/admin/BatchJobModal";
import { showErrorToast } from "@/lib/utils/toastUtils";

export default function BatchManagementPage() {
  const router = useRouter();
  const [jobs, setJobs] = useState<BatchJob[]>([]);
  const [filteredJobs, setFilteredJobs] = useState<BatchJob[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [jobTypes, setJobTypes] = useState<Array<{ value: string; label: string }>>([]);
  
  // 모달 상태
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedJob, setSelectedJob] = useState<BatchJob | null>(null);
  const [isBatchTypeModalOpen, setIsBatchTypeModalOpen] = useState(false);

  useEffect(() => {
    loadJobs();
    loadJobTypes();
  }, []);

  useEffect(() => {
    filterJobs();
  }, [jobs, searchTerm, statusFilter, typeFilter]);

  const loadJobs = async () => {
    setIsLoading(true);
    try {
      const data = await BatchAPI.getBatchJobs();
      setJobs(data);
    } catch (error) {
      console.error("배치 작업 목록 조회 오류:", error);
      showErrorToast("배치 작업 목록을 불러오는 데 실패했습니다", error, { guidance: "네트워크 연결을 확인해 주세요." });
    } finally {
      setIsLoading(false);
    }
  };

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

  const filterJobs = () => {
    let filtered = jobs;

    // 검색어 필터
    if (searchTerm) {
      filtered = filtered.filter(job =>
        job.job_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        job.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 상태 필터
    if (statusFilter !== "all") {
      filtered = filtered.filter(job => job.is_active === statusFilter);
    }

    // 타입 필터
    if (typeFilter !== "all") {
      filtered = filtered.filter(job => job.job_type === typeFilter);
    }

    setFilteredJobs(filtered);
  };

  const handleCreate = () => {
    setIsBatchTypeModalOpen(true);
  };

  const handleBatchTypeSelect = (type: 'db-to-db' | 'restapi-to-db') => {
    console.log("배치 타입 선택:", type);
    setIsBatchTypeModalOpen(false);
    
    if (type === 'db-to-db') {
      // 기존 배치 생성 모달 열기
      console.log("DB → DB 배치 모달 열기");
      setSelectedJob(null);
      setIsModalOpen(true);
    } else if (type === 'restapi-to-db') {
      // 새로운 REST API 배치 페이지로 이동
      console.log("REST API → DB 페이지로 이동:", '/admin/batch-management-new');
      router.push('/admin/batch-management-new');
    }
  };

  const handleEdit = (job: BatchJob) => {
    setSelectedJob(job);
    setIsModalOpen(true);
  };

  const handleDelete = async (job: BatchJob) => {
    if (!confirm(`"${job.job_name}" 배치 작업을 삭제하시겠습니까?`)) {
      return;
    }

    try {
      await BatchAPI.deleteBatchJob(job.id!);
      toast.success("배치 작업이 삭제되었습니다.");
      loadJobs();
    } catch (error) {
      console.error("배치 작업 삭제 오류:", error);
      showErrorToast("배치 작업 삭제에 실패했습니다", error, { guidance: "잠시 후 다시 시도해 주세요." });
    }
  };

  const handleExecute = async (job: BatchJob) => {
    try {
      await BatchAPI.executeBatchJob(job.id!);
      toast.success(`"${job.job_name}" 배치 작업을 실행했습니다.`);
    } catch (error) {
      console.error("배치 작업 실행 오류:", error);
      showErrorToast("배치 작업 실행에 실패했습니다", error, { guidance: "배치 설정을 확인해 주세요." });
    }
  };

  const handleModalSave = () => {
    loadJobs();
  };

  const getStatusBadge = (isActive: string) => {
    return isActive === "Y" ? (
      <Badge variant="default">활성</Badge>
    ) : (
      <Badge variant="secondary">비활성</Badge>
    );
  };

  const getTypeBadge = (type: string) => {
    const option = jobTypes.find(opt => opt.value === type);
    return (
      <Badge variant="outline">{option?.label || type}</Badge>
    );
  };

  const getSuccessRate = (job: BatchJob) => {
    if (job.execution_count === 0) return 100;
    return Math.round((job.success_count / job.execution_count) * 100);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">배치 관리</h1>
          <p className="text-muted-foreground">
            스케줄된 배치 작업을 관리하고 실행 상태를 모니터링합니다.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => window.open('/admin/monitoring', '_blank')}>
            <BarChart3 className="h-4 w-4 mr-2" />
            모니터링
          </Button>
          <Button onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            새 배치 작업
          </Button>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">총 작업</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{jobs.length}</div>
            <p className="text-xs text-muted-foreground">
              활성: {jobs.filter(j => j.is_active === 'Y').length}개
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">총 실행</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {jobs.reduce((sum, job) => sum + job.execution_count, 0)}
            </div>
            <p className="text-xs text-muted-foreground">누적 실행 횟수</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">성공</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-success">
              {jobs.reduce((sum, job) => sum + job.success_count, 0)}
            </div>
            <p className="text-xs text-muted-foreground">총 성공 횟수</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">실패</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-destructive">
              {jobs.reduce((sum, job) => sum + job.failure_count, 0)}
            </div>
            <p className="text-xs text-muted-foreground">총 실패 횟수</p>
          </CardContent>
        </Card>
      </div>

      {/* 필터 및 검색 */}
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="relative w-full sm:w-[300px]">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="작업명, 설명으로 검색..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="h-10 pl-10 text-sm"
            />
          </div>

          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="h-10 w-full sm:w-[160px]">
              <SelectValue placeholder="상태" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              <SelectItem value="Y">활성</SelectItem>
              <SelectItem value="N">비활성</SelectItem>
            </SelectContent>
          </Select>

          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger className="h-10 w-full sm:w-[160px]">
              <SelectValue placeholder="작업 타입" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 타입</SelectItem>
              {jobTypes.map((type) => (
                <SelectItem key={type.value} value={type.value}>
                  {type.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Button variant="outline" onClick={loadJobs} disabled={isLoading} className="h-10 w-full sm:w-auto">
          <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
          새로고침
        </Button>
      </div>

      {/* 배치 작업 목록 제목 */}
      <div className="text-sm text-muted-foreground">
        총 <span className="font-semibold text-foreground">{filteredJobs.length}</span>개
      </div>

      {isLoading ? (
        <>
          {/* 데스크톱 스켈레톤 */}
          <div className="hidden rounded-lg border bg-card shadow-sm lg:block">
            <Table>
              <TableHeader>
                <TableRow className="border-b bg-muted/50 hover:bg-muted/50">
                  <TableHead className="h-12 text-sm font-semibold">작업명</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">타입</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">스케줄</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">상태</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">실행 통계</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">성공률</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">마지막 실행</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i} className="border-b">
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-32"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-16"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-24"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-12"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-20"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-10"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-28"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 animate-pulse rounded bg-muted w-8"></div></TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {/* 모바일 스켈레톤 */}
          <div className="grid gap-4 sm:grid-cols-2 lg:hidden">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="rounded-lg border bg-card p-4 shadow-sm">
                <div className="mb-4 flex items-start justify-between">
                  <div className="flex-1 space-y-2">
                    <div className="h-5 w-32 animate-pulse rounded bg-muted"></div>
                    <div className="h-4 w-24 animate-pulse rounded bg-muted"></div>
                  </div>
                  <div className="h-6 w-12 animate-pulse rounded bg-muted"></div>
                </div>
                <div className="space-y-2 border-t pt-4">
                  {Array.from({ length: 3 }).map((_, j) => (
                    <div key={j} className="flex justify-between">
                      <div className="h-4 w-16 animate-pulse rounded bg-muted"></div>
                      <div className="h-4 w-24 animate-pulse rounded bg-muted"></div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </>
      ) : filteredJobs.length === 0 ? (
        <div className="flex h-32 items-center justify-center rounded-lg border bg-card text-sm text-muted-foreground">
          {jobs.length === 0 ? "배치 작업이 없습니다." : "검색 결과가 없습니다."}
        </div>
      ) : (
        <>
          {/* 데스크톱 테이블 */}
          <div className="hidden rounded-lg border bg-card shadow-sm lg:block">
            <Table>
              <TableHeader>
                <TableRow className="border-b bg-muted/50 hover:bg-muted/50">
                  <TableHead className="h-12 text-sm font-semibold">작업명</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">타입</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">스케줄</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">상태</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">실행 통계</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">성공률</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">마지막 실행</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredJobs.map((job) => (
                  <TableRow key={job.id} className="border-b transition-colors hover:bg-muted/50">
                    <TableCell className="h-16 text-sm">
                      <div>
                        <div className="font-medium">{job.job_name}</div>
                        {job.description && (
                          <div className="text-xs text-muted-foreground">{job.description}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell className="h-16 text-sm">{getTypeBadge(job.job_type)}</TableCell>
                    <TableCell className="h-16 font-mono text-sm">{job.schedule_cron || "-"}</TableCell>
                    <TableCell className="h-16 text-sm">{getStatusBadge(job.is_active)}</TableCell>
                    <TableCell className="h-16 text-sm">
                      <div>
                        <div>총 {job.execution_count}회</div>
                        <div className="text-xs text-muted-foreground">
                          성공 {job.success_count} / 실패 {job.failure_count}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell className="h-16 text-sm">
                      <span className={`font-medium ${
                        getSuccessRate(job) >= 90 ? 'text-success' :
                        getSuccessRate(job) >= 70 ? 'text-warning' : 'text-destructive'
                      }`}>
                        {getSuccessRate(job)}%
                      </span>
                    </TableCell>
                    <TableCell className="h-16 text-sm">
                      {job.last_executed_at
                        ? new Date(job.last_executed_at).toLocaleString()
                        : "-"}
                    </TableCell>
                    <TableCell className="h-16 text-sm">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" className="h-8 w-8 p-0">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => handleEdit(job)}>
                            <Edit className="h-4 w-4 mr-2" />
                            수정
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => handleExecute(job)}
                            disabled={job.is_active !== "Y"}
                          >
                            <Play className="h-4 w-4 mr-2" />
                            실행
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => handleDelete(job)}>
                            <Trash2 className="h-4 w-4 mr-2" />
                            삭제
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 */}
          <div className="grid gap-4 sm:grid-cols-2 lg:hidden">
            {filteredJobs.map((job) => (
              <div
                key={job.id}
                className="rounded-lg border bg-card p-4 shadow-sm transition-colors hover:bg-muted/50"
              >
                <div className="mb-3 flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <h3 className="truncate text-base font-semibold">{job.job_name}</h3>
                    {job.description && (
                      <p className="mt-0.5 truncate text-sm text-muted-foreground">{job.description}</p>
                    )}
                  </div>
                  <div className="ml-2 shrink-0">{getStatusBadge(job.is_active)}</div>
                </div>
                <div className="space-y-1.5 border-t pt-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">타입</span>
                    <span>{getTypeBadge(job.job_type)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">스케줄</span>
                    <span className="font-mono text-xs">{job.schedule_cron || "-"}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">실행 횟수</span>
                    <span className="font-medium">{job.execution_count}회</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">성공률</span>
                    <span className={`font-medium ${
                      getSuccessRate(job) >= 90 ? 'text-success' :
                      getSuccessRate(job) >= 70 ? 'text-warning' : 'text-destructive'
                    }`}>
                      {getSuccessRate(job)}%
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">마지막 실행</span>
                    <span className="text-xs">
                      {job.last_executed_at
                        ? new Date(job.last_executed_at).toLocaleDateString()
                        : "-"}
                    </span>
                  </div>
                </div>
                <div className="mt-3 flex gap-2 border-t pt-3">
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-9 flex-1 gap-2 text-sm"
                    onClick={() => handleEdit(job)}
                  >
                    <Edit className="h-4 w-4" />
                    수정
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-9 flex-1 gap-2 text-sm"
                    onClick={() => handleExecute(job)}
                    disabled={job.is_active !== "Y"}
                  >
                    <Play className="h-4 w-4" />
                    실행
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    className="h-9 w-9 p-0 text-destructive hover:text-destructive"
                    onClick={() => handleDelete(job)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {/* 배치 타입 선택 모달 */}
      {isBatchTypeModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <Card className="mx-4 w-full max-w-2xl">
            <CardHeader>
              <CardTitle className="text-center">배치 타입 선택</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                {/* DB → DB */}
                <div
                  className="cursor-pointer rounded-lg border p-6 transition-all hover:border-primary hover:bg-muted/50"
                  onClick={() => handleBatchTypeSelect('db-to-db')}
                >
                  <div className="mb-4 flex items-center justify-center">
                    <Database className="mr-2 h-8 w-8 text-primary" />
                    <ArrowRight className="mr-2 h-6 w-6 text-muted-foreground" />
                    <Database className="h-8 w-8 text-primary" />
                  </div>
                  <div className="text-center">
                    <div className="mb-2 text-lg font-medium">DB → DB</div>
                    <div className="text-sm text-muted-foreground">데이터베이스 간 데이터 동기화</div>
                  </div>
                </div>

                {/* REST API → DB */}
                <div
                  className="cursor-pointer rounded-lg border p-6 transition-all hover:border-primary hover:bg-muted/50"
                  onClick={() => handleBatchTypeSelect('restapi-to-db')}
                >
                  <div className="mb-4 flex items-center justify-center">
                    <Globe className="mr-2 h-8 w-8 text-success" />
                    <ArrowRight className="mr-2 h-6 w-6 text-muted-foreground" />
                    <Database className="h-8 w-8 text-success" />
                  </div>
                  <div className="text-center">
                    <div className="mb-2 text-lg font-medium">REST API → DB</div>
                    <div className="text-sm text-muted-foreground">REST API에서 데이터베이스로 데이터 수집</div>
                  </div>
                </div>
              </div>

              <div className="flex justify-center pt-4">
                <Button
                  variant="outline"
                  onClick={() => setIsBatchTypeModalOpen(false)}
                >
                  취소
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 배치 작업 모달 */}
      <BatchJobModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSave={handleModalSave}
        job={selectedJob}
      />
    </div>
  );
}
