"use client";

import React, { useState, useEffect, useCallback } from "react";
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 { Switch } from "@/components/ui/switch";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Search,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  Factory,
  CheckCircle2,
  XCircle,
  MinusCircle,
  Building2,
  Activity,
  Users,
  Plus,
  Trash2,
  Clock,
  CalendarOff,
  Settings,
  List,
  KeyRound,
  Send,
} from "lucide-react";
import {
  getSmartFactoryLogs,
  getSmartFactoryLogStats,
  getSchedules,
  upsertSchedule,
  deleteSchedule,
  getTodayPlan,
  getHolidays,
  addHoliday,
  deleteHoliday,
  getApiKeys,
  saveApiKey,
  deleteApiKey,
  getCompanyUsers,
  sendNow,
  SmartFactoryLogEntry,
  SmartFactoryLogFilters,
  SmartFactoryLogStats,
  ApiKeyEntry,
  CompanyUser,
  SmartFactorySchedule,
  SmartFactoryHoliday,
  TodayPlanEntry,
} from "@/lib/api/smartFactoryLog";
import { getCompanyList } from "@/lib/api/company";
import { useAuth } from "@/hooks/useAuth";
import { Company } from "@/types/company";

const STATUS_CONFIG = {
  SUCCESS: { label: "성공", variant: "success" as const, icon: CheckCircle2 },
  FAIL: { label: "실패", variant: "destructive" as const, icon: XCircle },
  SKIPPED: { label: "건너뜀", variant: "secondary" as const, icon: MinusCircle },
};

export default function SmartFactoryLogPage() {
  const { user } = useAuth();
  const [logs, setLogs] = useState<SmartFactoryLogEntry[]>([]);
  const [stats, setStats] = useState<SmartFactoryLogStats | null>(null);
  const [companies, setCompanies] = useState<Company[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  // 스케줄 관련
  const [schedules, setSchedules] = useState<SmartFactorySchedule[]>([]);
  const [todayPlan, setTodayPlan] = useState<TodayPlanEntry[]>([]);
  const [holidays, setHolidays] = useState<SmartFactoryHoliday[]>([]);
  const [scheduleDialogOpen, setScheduleDialogOpen] = useState(false);
  const [editingSchedule, setEditingSchedule] = useState({
    companyCode: "",
    isActive: true,
    timeStart: "08:30",
    timeEnd: "17:30",
    excludeWeekend: true,
    excludeHolidays: true,
    dailyCount: 1,
  });
  const [apiKeys, setApiKeys] = useState<ApiKeyEntry[]>([]);
  const [editingKey, setEditingKey] = useState({ companyCode: "", apiKey: "" });
  const [keyDialogOpen, setKeyDialogOpen] = useState(false);
  // 즉시 전송
  const [sendCompany, setSendCompany] = useState("");
  const [sendUsers, setSendUsers] = useState<CompanyUser[]>([]);
  const [selectedUserIds, setSelectedUserIds] = useState<Set<string>>(new Set());
  const [sendTimeStart, setSendTimeStart] = useState("08:30");
  const [sendTimeEnd, setSendTimeEnd] = useState("17:30");
  const [sending, setSending] = useState(false);

  const [newHoliday, setNewHoliday] = useState({ date: "", name: "" });
  const [holidayYear, setHolidayYear] = useState(String(new Date().getFullYear()));
  const [holidayPage, setHolidayPage] = useState(1);
  const HOLIDAY_PER_PAGE = 20;

  const [filters, setFilters] = useState<SmartFactoryLogFilters>({
    companyCode: "",
    sendStatus: "",
    search: "",
    dateFrom: "",
    dateTo: "",
    page: 1,
    limit: 50,
  });

  useEffect(() => { getCompanyList().then(setCompanies).catch(() => {}); }, []);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const [logRes, statsRes] = await Promise.all([
        getSmartFactoryLogs(filters),
        getSmartFactoryLogStats(filters.companyCode || undefined, 30),
      ]);
      if (logRes.success) { setLogs(logRes.data); setTotal(logRes.total); }
      if (statsRes.success) setStats(statsRes.data);
    } catch (error) {
      console.error("스마트공장 로그 조회 실패:", error);
    } finally { setLoading(false); }
  }, [filters]);

  useEffect(() => { fetchLogs(); }, [fetchLogs]);

  const fetchSchedules = useCallback(async () => {
    try {
      const [schedRes, planRes, holRes, keyRes] = await Promise.all([
        getSchedules(), getTodayPlan(), getHolidays(), getApiKeys(),
      ]);
      if (schedRes.success) setSchedules(schedRes.data);
      if (planRes.success) setTodayPlan(planRes.data);
      if (holRes.success) setHolidays(holRes.data);
      if (keyRes.success) setApiKeys(keyRes.data);
    } catch (e) { console.error("스케줄 조회 실패:", e); }
  }, []);

  useEffect(() => { fetchSchedules(); }, [fetchSchedules]);

  const totalPages = Math.ceil(total / (filters.limit || 50));
  const handleFilterChange = (key: keyof SmartFactoryLogFilters, value: string) => {
    setFilters((prev) => ({ ...prev, [key]: value, page: 1 }));
  };
  const formatDateStr = (dateStr: string) => {
    if (!dateStr) return "-";
    return new Date(dateStr).toLocaleString("ko-KR", {
      year: "numeric", month: "2-digit", day: "2-digit",
      hour: "2-digit", minute: "2-digit", second: "2-digit",
    });
  };

  const handleSendCompanyChange = async (companyCode: string) => {
    setSendCompany(companyCode);
    setSelectedUserIds(new Set());
    if (!companyCode) { setSendUsers([]); return; }
    try {
      const res = await getCompanyUsers(companyCode);
      if (res.success) setSendUsers(res.data);
    } catch { setSendUsers([]); }
  };

  const handleSendNow = async () => {
    if (!sendCompany || selectedUserIds.size === 0) return;
    setSending(true);
    try {
      const res = await sendNow({
        companyCode: sendCompany,
        userIds: Array.from(selectedUserIds),
      });
      if (res.success) {
        alert(res.message);
        fetchLogs();
      }
    } catch (e) {
      console.error("즉시 전송 실패:", e);
      alert("전송에 실패했습니다.");
    } finally {
      setSending(false);
    }
  };

  const [scheduleError, setScheduleError] = useState("");
  const handleSaveSchedule = async () => {
    if (!editingSchedule.companyCode) return;
    const keyInfo = apiKeys.find((k) => k.companyCode === editingSchedule.companyCode);
    if (!keyInfo?.hasDbKey && !keyInfo?.hasEnvKey) {
      setScheduleError("해당 회사의 API 키가 등록되지 않았습니다. API 키 관리 탭에서 먼저 등록해주세요.");
      return;
    }
    setScheduleError("");
    try { await upsertSchedule(editingSchedule); setScheduleDialogOpen(false); fetchSchedules(); }
    catch (e) { console.error("스케줄 저장 실패:", e); }
  };
  const handleDeleteSchedule = async (companyCode: string) => {
    if (!confirm("스케줄을 삭제하시겠습니까?")) return;
    try { await deleteSchedule(companyCode); fetchSchedules(); }
    catch (e) { console.error("스케줄 삭제 실패:", e); }
  };
  const handleAddHoliday = async () => {
    if (!newHoliday.date || !newHoliday.name) return;
    try { await addHoliday(newHoliday.date, newHoliday.name); setNewHoliday({ date: "", name: "" }); fetchSchedules(); }
    catch (e) { console.error("공휴일 추가 실패:", e); }
  };
  const handleToggleSchedule = async (s: SmartFactorySchedule) => {
    try {
      await upsertSchedule({
        companyCode: s.company_code, isActive: !s.is_active,
        timeStart: s.time_start, timeEnd: s.time_end,
        excludeWeekend: s.exclude_weekend, excludeHolidays: s.exclude_holidays, dailyCount: s.daily_count || 1,
      });
      fetchSchedules();
    } catch (e) { console.error("스케줄 토글 실패:", e); }
  };

  if (user && user.userType !== "SUPER_ADMIN" && user.companyCode !== "*") {
    return (
      <div className="flex items-center justify-center h-[60vh]">
        <p className="text-muted-foreground">최고 관리자만 접근할 수 있습니다.</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-[calc(100vh-64px)] overflow-hidden">
      {/* 헤더 */}
      <div className="flex items-center justify-between px-6 pt-6 pb-4 shrink-0">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Factory className="h-6 w-6" />
            스마트공장 활용 로그
          </h1>
          <p className="text-muted-foreground text-sm mt-1">
            log.smart-factory.kr 전송 로그 관리 및 자동 전송 스케줄
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={() => { fetchLogs(); fetchSchedules(); }} disabled={loading}>
          <RefreshCw className={`h-4 w-4 mr-1 ${loading ? "animate-spin" : ""}`} />
          새로고침
        </Button>
      </div>

      {/* 탭 */}
      <Tabs defaultValue="logs" className="flex flex-col flex-1 overflow-hidden px-6">
        <TabsList>
          <TabsTrigger value="logs" className="gap-1.5">
            <List className="h-4 w-4" />
            전송 기록
          </TabsTrigger>
          <TabsTrigger value="schedule" className="gap-1.5">
            <Settings className="h-4 w-4" />
            스케줄 설정
          </TabsTrigger>
          <TabsTrigger value="sendnow" className="gap-1.5">
            <Send className="h-4 w-4" />
            즉시 전송
          </TabsTrigger>
          <TabsTrigger value="apikeys" className="gap-1.5">
            <KeyRound className="h-4 w-4" />
            API 키 관리
          </TabsTrigger>
          <TabsTrigger value="holidays" className="gap-1.5">
            <CalendarOff className="h-4 w-4" />
            공휴일 관리
          </TabsTrigger>
        </TabsList>

        {/* ─── 탭 1: 전송 기록 ─── */}
        <TabsContent value="logs" className="overflow-y-auto flex-1 pb-6">
         <div className="space-y-6 pt-4">
          {/* 통계 카드 */}
          {stats && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-primary/10 rounded-lg"><Activity className="h-5 w-5 text-primary" /></div>
                    <div>
                      <p className="text-sm text-muted-foreground">최근 30일 전체</p>
                      <p className="text-2xl font-bold">{stats.total.toLocaleString()}건</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-green-100 rounded-lg"><CheckCircle2 className="h-5 w-5 text-green-600" /></div>
                    <div>
                      <p className="text-sm text-muted-foreground">전송 성공</p>
                      <p className="text-2xl font-bold text-green-600">
                        {(stats.statusCounts.find((s) => s.status === "SUCCESS")?.count || 0).toLocaleString()}건
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-red-100 rounded-lg"><XCircle className="h-5 w-5 text-red-600" /></div>
                    <div>
                      <p className="text-sm text-muted-foreground">전송 실패</p>
                      <p className="text-2xl font-bold text-red-600">
                        {(stats.statusCounts.find((s) => s.status === "FAIL")?.count || 0).toLocaleString()}건
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="pt-6">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-blue-100 rounded-lg"><Building2 className="h-5 w-5 text-blue-600" /></div>
                    <div>
                      <p className="text-sm text-muted-foreground">활용 회사</p>
                      <p className="text-2xl font-bold text-blue-600">{stats.companyCounts.length}개사</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* 회사별 현황 */}
          {stats && stats.companyCounts.length > 0 && (
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base flex items-center gap-2">
                  <Users className="h-4 w-4" />
                  회사별 전송 현황 (최근 30일)
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                  {stats.companyCounts.map((c) => (
                    <button
                      key={c.companyCode}
                      className={`p-3 rounded-lg border text-left hover:bg-accent transition-colors ${
                        filters.companyCode === c.companyCode ? "border-primary bg-primary/5" : ""
                      }`}
                      onClick={() => handleFilterChange("companyCode", filters.companyCode === c.companyCode ? "" : c.companyCode)}
                    >
                      <p className="text-xs text-muted-foreground truncate">{c.companyName}</p>
                      <p className="text-lg font-semibold">{c.count.toLocaleString()}건</p>
                    </button>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* 필터 */}
          <Card>
            <CardContent className="pt-6">
              <div className="flex flex-wrap items-end gap-3">
                <div className="flex-1 min-w-[200px]">
                  <label className="text-xs text-muted-foreground mb-1 block">검색</label>
                  <div className="relative">
                    <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input placeholder="사용자, IP, 에러메시지..." className="pl-9"
                      value={filters.search || ""} onChange={(e) => handleFilterChange("search", e.target.value)} />
                  </div>
                </div>
                <div className="w-[180px]">
                  <label className="text-xs text-muted-foreground mb-1 block">회사</label>
                  <Select value={filters.companyCode || "all"} onValueChange={(v) => handleFilterChange("companyCode", v === "all" ? "" : v)}>
                    <SelectTrigger><SelectValue placeholder="전체 회사" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체 회사</SelectItem>
                      {companies.map((c) => (<SelectItem key={c.company_code} value={c.company_code}>{c.company_name}</SelectItem>))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="w-[140px]">
                  <label className="text-xs text-muted-foreground mb-1 block">상태</label>
                  <Select value={filters.sendStatus || "all"} onValueChange={(v) => handleFilterChange("sendStatus", v === "all" ? "" : v)}>
                    <SelectTrigger><SelectValue placeholder="전체" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      <SelectItem value="SUCCESS">성공</SelectItem>
                      <SelectItem value="FAIL">실패</SelectItem>
                      <SelectItem value="SKIPPED">건너뜀</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="w-[160px]">
                  <label className="text-xs text-muted-foreground mb-1 block">시작일</label>
                  <Input type="date" value={filters.dateFrom || ""} onChange={(e) => handleFilterChange("dateFrom", e.target.value)} />
                </div>
                <div className="w-[160px]">
                  <label className="text-xs text-muted-foreground mb-1 block">종료일</label>
                  <Input type="date" value={filters.dateTo || ""} onChange={(e) => handleFilterChange("dateTo", e.target.value)} />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 로그 테이블 */}
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-base">전송 기록 ({total.toLocaleString()}건)</CardTitle>
                <Select value={String(filters.limit || 50)} onValueChange={(v) => setFilters((prev) => ({ ...prev, limit: parseInt(v, 10), page: 1 }))}>
                  <SelectTrigger className="w-[100px] h-8 text-xs"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="20">20건</SelectItem>
                    <SelectItem value="50">50건</SelectItem>
                    <SelectItem value="100">100건</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent>
              <div className="border rounded-md">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[50px]">No</TableHead>
                      <TableHead className="w-[120px]">회사</TableHead>
                      <TableHead className="w-[120px]">사용자</TableHead>
                      <TableHead className="w-[100px]">유형</TableHead>
                      <TableHead className="w-[130px]">접속 IP</TableHead>
                      <TableHead className="w-[90px]">상태</TableHead>
                      <TableHead className="w-[60px]">응답</TableHead>
                      <TableHead>에러 메시지</TableHead>
                      <TableHead className="w-[170px]">전송 시각</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading ? (
                      <TableRow><TableCell colSpan={9} className="text-center py-12 text-muted-foreground">로딩 중...</TableCell></TableRow>
                    ) : logs.length === 0 ? (
                      <TableRow><TableCell colSpan={9} className="text-center py-12 text-muted-foreground">로그가 없습니다.</TableCell></TableRow>
                    ) : (
                      logs.map((log, idx) => {
                        const statusConf = STATUS_CONFIG[log.send_status as keyof typeof STATUS_CONFIG] || STATUS_CONFIG.FAIL;
                        const StatusIcon = statusConf.icon;
                        return (
                          <TableRow key={log.id}>
                            <TableCell className="text-muted-foreground text-xs">
                              {total - ((filters.page || 1) - 1) * (filters.limit || 50) - idx}
                            </TableCell>
                            <TableCell><span className="text-xs">{log.company_name || log.company_code}</span></TableCell>
                            <TableCell>
                              <div>
                                <span className="text-sm">{log.user_name || "-"}</span>
                                <span className="text-xs text-muted-foreground block">{log.user_id}</span>
                              </div>
                            </TableCell>
                            <TableCell className="text-xs">{log.use_type}</TableCell>
                            <TableCell className="text-xs font-mono">{log.connect_ip}</TableCell>
                            <TableCell>
                              <Badge variant={statusConf.variant} className="gap-1 text-xs">
                                <StatusIcon className="h-3 w-3" />{statusConf.label}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-xs text-center">{log.response_status || "-"}</TableCell>
                            <TableCell className="text-xs text-muted-foreground max-w-[300px] truncate" title={log.error_message || ""}>
                              {log.error_message || "-"}
                            </TableCell>
                            <TableCell className="text-xs">{formatDateStr(log.created_at)}</TableCell>
                          </TableRow>
                        );
                      })
                    )}
                  </TableBody>
                </Table>
              </div>

              {totalPages > 1 && (
                <div className="flex items-center justify-between mt-4">
                  <p className="text-sm text-muted-foreground">
                    {((filters.page || 1) - 1) * (filters.limit || 50) + 1}~
                    {Math.min((filters.page || 1) * (filters.limit || 50), total)} / {total.toLocaleString()}건
                  </p>
                  <div className="flex items-center gap-1">
                    <Button variant="outline" size="icon" className="h-8 w-8" disabled={(filters.page || 1) <= 1}
                      onClick={() => setFilters((prev) => ({ ...prev, page: (prev.page || 1) - 1 }))}><ChevronLeft className="h-4 w-4" /></Button>
                    <span className="text-sm px-2">{filters.page || 1} / {totalPages}</span>
                    <Button variant="outline" size="icon" className="h-8 w-8" disabled={(filters.page || 1) >= totalPages}
                      onClick={() => setFilters((prev) => ({ ...prev, page: (prev.page || 1) + 1 }))}><ChevronRight className="h-4 w-4" /></Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
         </div>
        </TabsContent>

        {/* ─── 탭 2: 스케줄 설정 ─── */}
        <TabsContent value="schedule" className="overflow-y-auto flex-1 pb-6">
         <div className="space-y-6 pt-4">
          {/* 오늘 실행 현황 */}
          {todayPlan.length > 0 && (
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
              {todayPlan.map((p) => {
                const companyName = schedules.find((s) => s.company_code === p.companyCode)?.company_name || p.companyCode;
                const pct = p.total > 0 ? Math.round((p.sent / p.total) * 100) : 0;
                return (
                  <Card key={p.companyCode}>
                    <CardContent className="pt-5 pb-4">
                      <p className="text-sm font-medium truncate">{companyName}</p>
                      <div className="mt-2 h-2 bg-muted rounded-full overflow-hidden">
                        <div className="h-full bg-green-500 rounded-full transition-all" style={{ width: `${pct}%` }} />
                      </div>
                      <p className="text-xs text-muted-foreground mt-1.5">
                        <span className="text-green-600 font-medium">{p.sent}</span> / {p.total}명 완료
                        {p.remaining > 0 && <span className="ml-1">({p.remaining}명 남음)</span>}
                      </p>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {/* 스케줄 테이블 */}
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-base flex items-center gap-2">
                  <Clock className="h-4 w-4" />
                  회사별 자동 전송 스케줄
                </CardTitle>
                <Button size="sm" onClick={() => {
                  setEditingSchedule({ companyCode: "", isActive: true, timeStart: "08:30", timeEnd: "17:30", excludeWeekend: true, excludeHolidays: true, dailyCount: 1 });
                  setScheduleError(""); setScheduleDialogOpen(true);
                }}>
                  <Plus className="h-4 w-4 mr-1" />스케줄 추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {schedules.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">등록된 스케줄이 없습니다. 스케줄을 추가하여 자동 전송을 시작하세요.</p>
              ) : (
                <div className="border rounded-md">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>회사</TableHead>
                        <TableHead className="w-[140px]">로그인 시간대</TableHead>
                        <TableHead className="w-[90px]">주말 제외</TableHead>
                        <TableHead className="w-[90px]">공휴일 제외</TableHead>
                        <TableHead className="w-[70px]">횟수</TableHead>
                        <TableHead className="w-[80px]">활성</TableHead>
                        <TableHead className="w-[160px]">동작</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {schedules.map((s) => (
                        <TableRow key={s.id}>
                          <TableCell className="font-medium text-sm">{s.company_name || s.company_code}</TableCell>
                          <TableCell className="text-sm">
                            <span className="flex items-center gap-1"><Clock className="h-3 w-3 text-muted-foreground" />{s.time_start} ~ {s.time_end}</span>
                          </TableCell>
                          <TableCell>{s.exclude_weekend ? <Badge variant="secondary">Y</Badge> : <span className="text-muted-foreground text-xs">N</span>}</TableCell>
                          <TableCell>{s.exclude_holidays ? <Badge variant="secondary">Y</Badge> : <span className="text-muted-foreground text-xs">N</span>}</TableCell>
                          <TableCell className="text-sm text-center">{s.daily_count || 1}회</TableCell>
                          <TableCell><Switch checked={s.is_active} onCheckedChange={() => handleToggleSchedule(s)} /></TableCell>
                          <TableCell>
                            <div className="flex items-center gap-1">
                              <Button variant="outline" size="icon" className="h-7 w-7" title="수정"
                                onClick={() => {
                                  setEditingSchedule({
                                    companyCode: s.company_code, isActive: s.is_active,
                                    timeStart: s.time_start, timeEnd: s.time_end,
                                    excludeWeekend: s.exclude_weekend, excludeHolidays: s.exclude_holidays, dailyCount: s.daily_count || 1,
                                  });
                                  setScheduleError(""); setScheduleDialogOpen(true);
                                }}>
                                <Settings className="h-3 w-3" />
                              </Button>
                              <Button variant="outline" size="icon" className="h-7 w-7 text-destructive" title="삭제"
                                onClick={() => handleDeleteSchedule(s.company_code)}>
                                <Trash2 className="h-3 w-3" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
         </div>
        </TabsContent>

        {/* ─── 탭 3: 즉시 전송 ─── */}
        <TabsContent value="sendnow" className="overflow-y-auto flex-1 pb-6">
         <div className="space-y-6 pt-4">
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                <Send className="h-4 w-4" />
                사용자 지정 즉시 전송
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* 회사 선택 + 시간대 */}
              <div className="flex flex-wrap items-end gap-3">
                <div className="w-[200px]">
                  <label className="text-xs text-muted-foreground mb-1 block">회사</label>
                  <Select value={sendCompany || "none"} onValueChange={(v) => handleSendCompanyChange(v === "none" ? "" : v)}>
                    <SelectTrigger><SelectValue placeholder="회사 선택" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none" disabled>회사 선택</SelectItem>
                      {companies.filter((c) => c.company_code !== "*").map((c) => (
                        <SelectItem key={c.company_code} value={c.company_code}>{c.company_name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <Button
                  onClick={handleSendNow}
                  disabled={sending || selectedUserIds.size === 0}
                >
                  {sending ? <RefreshCw className="h-4 w-4 mr-1 animate-spin" /> : <Send className="h-4 w-4 mr-1" />}
                  {selectedUserIds.size > 0 ? `${selectedUserIds.size}명 전송` : "전송"}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                선택한 사용자의 로그를 현재 시각으로 즉시 전송합니다.
              </p>

              {/* 사용자 목록 */}
              {sendCompany && (
                <div className="border rounded-md">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[50px]">
                          <input
                            type="checkbox"
                            className="rounded"
                            checked={sendUsers.length > 0 && selectedUserIds.size === sendUsers.length}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedUserIds(new Set(sendUsers.map((u) => u.user_id)));
                              } else {
                                setSelectedUserIds(new Set());
                              }
                            }}
                          />
                        </TableHead>
                        <TableHead>사용자 ID</TableHead>
                        <TableHead>이름</TableHead>
                        <TableHead>부서</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {sendUsers.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={4} className="text-center py-8 text-muted-foreground">
                            사용자가 없습니다.
                          </TableCell>
                        </TableRow>
                      ) : (
                        sendUsers.map((u) => (
                          <TableRow key={u.user_id} className="cursor-pointer" onClick={() => {
                            setSelectedUserIds((prev) => {
                              const next = new Set(prev);
                              if (next.has(u.user_id)) next.delete(u.user_id);
                              else next.add(u.user_id);
                              return next;
                            });
                          }}>
                            <TableCell>
                              <input
                                type="checkbox"
                                className="rounded"
                                checked={selectedUserIds.has(u.user_id)}
                                onChange={() => {}}
                              />
                            </TableCell>
                            <TableCell className="text-sm font-mono">{u.user_id}</TableCell>
                            <TableCell className="text-sm">{u.user_name}</TableCell>
                            <TableCell className="text-sm text-muted-foreground">{u.dept_name || "-"}</TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
         </div>
        </TabsContent>

        {/* ─── 탭 4: API 키 관리 ─── */}
        <TabsContent value="apikeys" className="overflow-y-auto flex-1 pb-6">
         <div className="space-y-6 pt-4">
          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-base flex items-center gap-2">
                  <KeyRound className="h-4 w-4" />
                  회사별 API 키 관리
                </CardTitle>
                <p className="text-sm text-muted-foreground">log.smart-factory.kr 인증키 (crtfcKey)</p>
              </div>
            </CardHeader>
            <CardContent>
              <div className="border rounded-md">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>회사</TableHead>
                      <TableHead>DB 키</TableHead>
                      <TableHead className="w-[100px]">환경변수</TableHead>
                      <TableHead className="w-[100px]">상태</TableHead>
                      <TableHead className="w-[140px]">동작</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {apiKeys.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">회사 정보를 불러오는 중...</TableCell>
                      </TableRow>
                    ) : (
                      apiKeys.map((k) => (
                        <TableRow key={k.companyCode}>
                          <TableCell className="font-medium text-sm">{k.companyName}</TableCell>
                          <TableCell>
                            {k.dbKey
                              ? <code className="text-xs bg-muted px-1.5 py-0.5 rounded break-all">{k.dbKey}</code>
                              : <span className="text-xs text-muted-foreground">-</span>}
                          </TableCell>
                          <TableCell>
                            {k.hasEnvKey
                              ? <Badge variant="secondary" className="text-xs">있음</Badge>
                              : <span className="text-xs text-muted-foreground">-</span>}
                          </TableCell>
                          <TableCell>
                            {k.hasDbKey || k.hasEnvKey
                              ? <Badge variant="success" className="text-xs">사용 가능</Badge>
                              : <Badge variant="destructive" className="text-xs">미설정</Badge>}
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-1">
                              <Button variant="outline" size="sm" className="h-7 text-xs"
                                onClick={() => { setEditingKey({ companyCode: k.companyCode, apiKey: "" }); setKeyDialogOpen(true); }}>
                                {k.hasDbKey ? "변경" : "등록"}
                              </Button>
                              {k.hasDbKey && (
                                <Button variant="outline" size="sm" className="h-7 text-xs text-destructive"
                                  onClick={async () => {
                                    if (!confirm(`${k.companyName}의 DB 키를 삭제하시겠습니까? 환경변수 키가 있으면 그것으로 폴백됩니다.`)) return;
                                    await deleteApiKey(k.companyCode);
                                    fetchSchedules();
                                  }}>
                                  삭제
                                </Button>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
              <p className="text-xs text-muted-foreground mt-3">
                DB 키가 우선 사용됩니다. DB 키가 없으면 서버 환경변수(SMART_FACTORY_API_KEY_회사코드)를 사용합니다.
              </p>
            </CardContent>
          </Card>
         </div>
        </TabsContent>

        {/* ─── 탭 4: 공휴일 관리 ─── */}
        <TabsContent value="holidays" className="flex flex-col flex-1 overflow-hidden">
          {/* 상단 고정: 추가 폼 + 연도 필터 */}
          <div className="shrink-0 pt-4 pb-4 space-y-4">
            <div className="flex items-end gap-3 flex-wrap">
              <div>
                <label className="text-xs text-muted-foreground mb-1 block">날짜</label>
                <Input type="date" value={newHoliday.date}
                  onChange={(e) => setNewHoliday((p) => ({ ...p, date: e.target.value }))} className="w-[170px]" />
              </div>
              <div>
                <label className="text-xs text-muted-foreground mb-1 block">공휴일명</label>
                <Input value={newHoliday.name}
                  onChange={(e) => setNewHoliday((p) => ({ ...p, name: e.target.value }))}
                  placeholder="예: 설날" className="w-[220px]" />
              </div>
              <Button size="sm" onClick={handleAddHoliday} disabled={!newHoliday.date || !newHoliday.name}>
                <Plus className="h-4 w-4 mr-1" />추가
              </Button>
              <div className="ml-auto flex items-end gap-2">
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">연도</label>
                  <Select value={holidayYear} onValueChange={(v) => { setHolidayYear(v); setHolidayPage(1); }}>
                    <SelectTrigger className="w-[100px]"><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      {Array.from(new Set(holidays.map((h) => h.holiday_date.substring(0, 4)))).sort().map((y) => (
                        <SelectItem key={y} value={y}>{y}년</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </div>

          {/* 스크롤 영역: 테이블 + 페이지네이션 */}
          <div className="flex-1 overflow-y-auto pb-6">
            {(() => {
              const filtered = holidayYear === "all"
                ? holidays
                : holidays.filter((h) => h.holiday_date.startsWith(holidayYear));
              const totalHolidayPages = Math.ceil(filtered.length / HOLIDAY_PER_PAGE);
              const paged = filtered.slice((holidayPage - 1) * HOLIDAY_PER_PAGE, holidayPage * HOLIDAY_PER_PAGE);

              return filtered.length === 0 ? (
                <Card>
                  <CardContent className="py-8">
                    <p className="text-sm text-muted-foreground text-center">등록된 공휴일이 없습니다.</p>
                  </CardContent>
                </Card>
              ) : (
                <Card>
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-base flex items-center gap-2">
                        <CalendarOff className="h-4 w-4" />
                        {holidayYear === "all" ? "전체" : `${holidayYear}년`} 공휴일
                      </CardTitle>
                      <p className="text-sm text-muted-foreground">{filtered.length}일</p>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="border rounded-md">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[140px]">날짜</TableHead>
                            <TableHead className="w-[100px]">요일</TableHead>
                            <TableHead>공휴일명</TableHead>
                            <TableHead className="w-[60px]"></TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {paged.map((h) => {
                            const d = new Date(h.holiday_date + "T00:00:00");
                            const dayName = ["일", "월", "화", "수", "목", "금", "토"][d.getDay()];
                            const isWeekend = d.getDay() === 0 || d.getDay() === 6;
                            return (
                              <TableRow key={h.id}>
                                <TableCell className="text-sm font-mono">{h.holiday_date.substring(0, 10)}</TableCell>
                                <TableCell>
                                  <span className={isWeekend ? "text-red-500" : ""}>{dayName}요일</span>
                                </TableCell>
                                <TableCell className="text-sm">{h.holiday_name}</TableCell>
                                <TableCell>
                                  <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-destructive"
                                    onClick={async () => { await deleteHoliday(h.id); fetchSchedules(); }}>
                                    <Trash2 className="h-3 w-3" />
                                  </Button>
                                </TableCell>
                              </TableRow>
                            );
                          })}
                        </TableBody>
                      </Table>
                    </div>

                    {totalHolidayPages > 1 && (
                      <div className="flex items-center justify-between mt-4">
                        <p className="text-sm text-muted-foreground">
                          {(holidayPage - 1) * HOLIDAY_PER_PAGE + 1}~{Math.min(holidayPage * HOLIDAY_PER_PAGE, filtered.length)} / {filtered.length}일
                        </p>
                        <div className="flex items-center gap-1">
                          <Button variant="outline" size="icon" className="h-8 w-8" disabled={holidayPage <= 1}
                            onClick={() => setHolidayPage((p) => p - 1)}><ChevronLeft className="h-4 w-4" /></Button>
                          <span className="text-sm px-2">{holidayPage} / {totalHolidayPages}</span>
                          <Button variant="outline" size="icon" className="h-8 w-8" disabled={holidayPage >= totalHolidayPages}
                            onClick={() => setHolidayPage((p) => p + 1)}><ChevronRight className="h-4 w-4" /></Button>
                        </div>
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })()}
          </div>
        </TabsContent>
      </Tabs>

      {/* 스케줄 추가/수정 Dialog */}
      <Dialog open={scheduleDialogOpen} onOpenChange={setScheduleDialogOpen}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader>
            <DialogTitle>{editingSchedule.companyCode && schedules.some((s) => s.company_code === editingSchedule.companyCode) ? "스케줄 수정" : "스케줄 추가"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-1 block">회사</label>
              <Select
                value={editingSchedule.companyCode || "none"}
                onValueChange={(v) => { setEditingSchedule((p) => ({ ...p, companyCode: v === "none" ? "" : v })); setScheduleError(""); }}
                disabled={!!editingSchedule.companyCode && schedules.some((s) => s.company_code === editingSchedule.companyCode)}
              >
                <SelectTrigger><SelectValue placeholder="회사 선택" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="none" disabled>회사 선택</SelectItem>
                  {companies.filter((c) => c.company_code !== "*").map((c) => (
                    <SelectItem key={c.company_code} value={c.company_code}>{c.company_name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium mb-1 block">로그인 시작</label>
                  <Input type="time" value={editingSchedule.timeStart} onChange={(e) => setEditingSchedule((p) => ({ ...p, timeStart: e.target.value }))} />
                </div>
                <div>
                  <label className="text-sm font-medium mb-1 block">로그인 종료</label>
                  <Input type="time" value={editingSchedule.timeEnd} onChange={(e) => setEditingSchedule((p) => ({ ...p, timeEnd: e.target.value }))} />
                </div>
              </div>
              <p className="text-xs text-muted-foreground mt-1.5">해당 시간대에 전 직원의 로그인 이력이 랜덤 시각으로 전송됩니다</p>
            </div>
            <div className="flex items-center justify-between">
              <label className="text-sm">주말(토/일) 제외</label>
              <Switch checked={editingSchedule.excludeWeekend} onCheckedChange={(v) => setEditingSchedule((p) => ({ ...p, excludeWeekend: v }))} />
            </div>
            <div className="flex items-center justify-between">
              <label className="text-sm">공휴일 제외</label>
              <Switch checked={editingSchedule.excludeHolidays} onCheckedChange={(v) => setEditingSchedule((p) => ({ ...p, excludeHolidays: v }))} />
            </div>
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm">일일 접속 횟수</label>
                <p className="text-xs text-muted-foreground">사용자별 하루 최대 접속/종료 쌍 수</p>
              </div>
              <Select value={String(editingSchedule.dailyCount)} onValueChange={(v) => setEditingSchedule((p) => ({ ...p, dailyCount: parseInt(v, 10) }))}>
                <SelectTrigger className="w-[80px]"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">1회</SelectItem>
                  <SelectItem value="2">2회</SelectItem>
                  <SelectItem value="3">3회</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          {scheduleError && (
            <p className="text-sm text-destructive px-6">{scheduleError}</p>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setScheduleDialogOpen(false)}>취소</Button>
            <Button onClick={handleSaveSchedule} disabled={!editingSchedule.companyCode}>저장</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* API 키 등록/변경 Dialog */}
      <Dialog open={keyDialogOpen} onOpenChange={setKeyDialogOpen}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader>
            <DialogTitle>API 키 {editingKey.companyCode ? "등록/변경" : ""}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-1 block">회사</label>
              <p className="text-sm">
                {apiKeys.find((k) => k.companyCode === editingKey.companyCode)?.companyName || editingKey.companyCode}
              </p>
            </div>
            <div>
              <label className="text-sm font-medium mb-1 block">API 키</label>
              <Input
                value={editingKey.apiKey}
                onChange={(e) => setEditingKey((p) => ({ ...p, apiKey: e.target.value }))}
                placeholder="스마트공장 인증키 (crtfcKey) 입력"
                className="font-mono text-sm"
              />
              <p className="text-xs text-muted-foreground mt-1">AES-256-GCM 암호화하여 저장됩니다</p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setKeyDialogOpen(false)}>취소</Button>
            <Button
              onClick={async () => {
                if (!editingKey.companyCode || !editingKey.apiKey) return;
                try {
                  await saveApiKey(editingKey.companyCode, editingKey.apiKey);
                  setKeyDialogOpen(false);
                  setEditingKey({ companyCode: "", apiKey: "" });
                  fetchSchedules();
                } catch (e) { console.error("API 키 저장 실패:", e); }
              }}
              disabled={!editingKey.apiKey}
            >
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
