"use client";

import { useState, useMemo, useRef, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Calendar } from "@/components/ui/calendar";
import { ReportListTable } from "@/components/report/ReportListTable";
import { ReportCreateModal } from "@/components/report/ReportCreateModal";
import { ReportCopyModal } from "@/components/report/ReportCopyModal";
import { ReportListPreviewModal } from "@/components/report/ReportListPreviewModal";
import {
  Plus,
  Search,
  LayoutGrid,
  List,
  FileText,
  Users,
  SlidersHorizontal,
  Check,
  Tag,
  CalendarDays,
  User,
  X,
} from "lucide-react";
import { useReportList } from "@/hooks/useReportList";
import { ReportMaster } from "@/types/report";
import { PieChart, Pie, Cell, Tooltip, BarChart, Bar, XAxis, LabelList } from "recharts";
import { REPORT_TYPE_COLORS, getTypeColorIndex, getTypeLabel, getTypeIcon } from "@/lib/reportTypeColors";
import { format, subDays, subMonths, startOfDay } from "date-fns";
import { ko } from "date-fns/locale";

const SEARCH_FIELD_OPTIONS = [
  { value: "report_type" as const, label: "카테고리", icon: Tag },
  { value: "report_name" as const, label: "리포트명", icon: FileText },
  { value: "updated_at" as const, label: "기간 검색", icon: CalendarDays },
  { value: "created_by" as const, label: "작성자", icon: User },
];

export default function ReportManagementPage() {
  const [searchText, setSearchText] = useState("");
  const [viewMode, setViewMode] = useState<"grid" | "list">("list");
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [copyTarget, setCopyTarget] = useState<ReportMaster | null>(null);
  const [viewTarget, setViewTarget] = useState<ReportMaster | null>(null);
  const [filterOpen, setFilterOpen] = useState(false);
  const [datePopoverOpen, setDatePopoverOpen] = useState(false);
  const [tempStartDate, setTempStartDate] = useState<Date | undefined>(undefined);
  const [tempEndDate, setTempEndDate] = useState<Date | undefined>(undefined);
  const filterRef = useRef<HTMLDivElement>(null);

  const {
    reports,
    total,
    typeSummary,
    recentActivity,
    recentTotal,
    page,
    limit,
    isLoading,
    searchField,
    startDate,
    endDate,
    refetch,
    setPage,
    setLimit,
    handleSearch,
    handleSearchFieldChange,
    handleDateRangeChange,
  } = useReportList();

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (filterRef.current && !filterRef.current.contains(e.target as Node)) {
        setFilterOpen(false);
        setDatePopoverOpen(false);
      }
    };
    if (filterOpen) document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [filterOpen]);

  const isDateFilterActive = searchField === "updated_at" && startDate && endDate;

  const handleDatePreset = useCallback((days: number) => {
    const end = new Date();
    const start = days === 0 ? startOfDay(end) : subDays(end, days);
    setTempStartDate(start);
    setTempEndDate(end);
  }, []);

  const handleMonthPreset = useCallback((months: number) => {
    const end = new Date();
    const start = subMonths(end, months);
    setTempStartDate(start);
    setTempEndDate(end);
  }, []);

  const handleApplyDateFilter = useCallback(() => {
    if (!tempStartDate || !tempEndDate) return;
    handleSearchFieldChange("updated_at");
    handleDateRangeChange(format(tempStartDate, "yyyy-MM-dd"), format(tempEndDate, "yyyy-MM-dd"));
    setDatePopoverOpen(false);
    setFilterOpen(false);
  }, [tempStartDate, tempEndDate, handleSearchFieldChange, handleDateRangeChange]);

  const handleClearDateFilter = useCallback(() => {
    setTempStartDate(undefined);
    setTempEndDate(undefined);
    handleSearchFieldChange("report_name");
    handleDateRangeChange("", "");
  }, [handleSearchFieldChange, handleDateRangeChange]);

  const typeData = useMemo(() => typeSummary.map(({ type, count }) => ({ type, value: count })), [typeSummary]);

  const authorStats = useMemo(() => {
    const map = new Map<string, number>();
    reports.forEach((r) => {
      const author = r.created_by || "미지정";
      map.set(author, (map.get(author) || 0) + 1);
    });
    return Array.from(map.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count)
      .slice(0, 3)
      .sort((a, b) => a.name.localeCompare(b.name, "ko"));
  }, [reports]);

  const authorCount = useMemo(() => new Set(reports.map((r) => r.created_by).filter(Boolean)).size, [reports]);

  const handleSearchClick = () => handleSearch(searchText);

  const handleViewModeChange = (mode: "grid" | "list") => {
    setViewMode(mode);
    setLimit(mode === "grid" ? 9 : 8);
    setPage(1);
  };

  const handleCreateNew = () => {
    setIsCreateOpen(true);
  };

  const currentFieldLabel = SEARCH_FIELD_OPTIONS.find((o) => o.value === searchField)?.label ?? "리포트명";

  return (
    <div className="report-page-content flex h-[calc(100vh-56px)] flex-col bg-gray-50">
      <div className="shrink-0 border-b bg-white">
          <div className="mx-6 py-2.5">
          <div className="mb-2 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <h1 className="text-xl font-bold text-gray-900">리포트 관리</h1>
              <span className="text-sm text-gray-400">리포트를 생성하고 관리합니다</span>
            </div>
          </div>

          <div className="flex items-center gap-2.5">
            <div className="relative w-full sm:w-[480px]">
              <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <Input
                placeholder={`${currentFieldLabel}(으)로 검색...`}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearchClick()}
                className="h-9 pl-9 text-sm"
              />
            </div>

            <Button
              onClick={handleSearchClick}
              size="icon"
              variant="outline"
              className="h-9 w-9 shrink-0"
              title="검색"
            >
              <Search className="h-4 w-4" />
            </Button>

            <div ref={filterRef} className="relative">
              <Button
                onClick={() => setFilterOpen(!filterOpen)}
                size="icon"
                variant="outline"
                className={`h-9 w-9 shrink-0 ${filterOpen || isDateFilterActive ? "border-blue-400 bg-blue-50 text-blue-600" : ""}`}
                title="검색 필터"
              >
                <SlidersHorizontal className="h-4 w-4" />
              </Button>

              {filterOpen && !datePopoverOpen && (
                <div className="absolute top-full right-0 z-50 mt-1.5 w-52 rounded-lg border border-gray-200 bg-white py-1.5 shadow-lg">
                  <div className="px-3.5 py-2 text-sm font-semibold text-gray-400">검색 기준</div>
                  {SEARCH_FIELD_OPTIONS.map((opt) => {
                    const Icon = opt.icon;
                    const isDateOption = opt.value === "updated_at";
                    return (
                      <button
                        key={opt.value}
                        onClick={() => {
                          if (isDateOption) {
                            setDatePopoverOpen(true);
                          } else {
                            handleSearchFieldChange(opt.value);
                            handleDateRangeChange("", "");
                            setFilterOpen(false);
                          }
                        }}
                        className={`flex w-full items-center gap-2.5 px-3.5 py-2.5 text-base transition-colors hover:bg-gray-50 ${
                          searchField === opt.value || (isDateOption && searchField === "updated_at")
                            ? "font-medium text-blue-600"
                            : "text-gray-700"
                        }`}
                      >
                        <Icon className="h-4 w-4 shrink-0" />
                        <span className="flex-1 text-left">{opt.label}</span>
                        {isDateOption && <span className="text-xs text-gray-400">&#9656;</span>}
                        {!isDateOption && searchField === opt.value && (
                          <Check className="h-4.5 w-4.5 shrink-0 text-blue-600" />
                        )}
                      </button>
                    );
                  })}
                </div>
              )}

              {filterOpen && datePopoverOpen && (
                <div
                  className="absolute top-full right-0 z-50 mt-1.5 rounded-lg border border-gray-200 bg-white shadow-lg"
                  onMouseDown={(e) => e.stopPropagation()}
                >
                  <div className="flex items-center justify-between border-b px-4 py-3">
                    <button
                      onClick={() => setDatePopoverOpen(false)}
                      className="text-sm text-gray-500 hover:text-gray-700"
                    >
                      &larr; 뒤로
                    </button>
                    <span className="text-sm font-semibold text-gray-700">기간 검색</span>
                    <div className="w-10" />
                  </div>

                  <div className="space-y-3 p-4">
                    <div className="flex gap-1.5">
                      {[
                        { label: "오늘", action: () => handleDatePreset(0) },
                        { label: "1주일", action: () => handleDatePreset(7) },
                        { label: "1개월", action: () => handleMonthPreset(1) },
                        { label: "3개월", action: () => handleMonthPreset(3) },
                      ].map((preset) => (
                        <button
                          key={preset.label}
                          onClick={preset.action}
                          className="flex-1 rounded-md border border-gray-200 px-2 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:border-blue-300 hover:bg-blue-50 hover:text-blue-600"
                        >
                          {preset.label}
                        </button>
                      ))}
                    </div>

                    <div className="flex gap-4">
                      <div className="flex-1">
                        <label className="mb-1.5 block text-xs font-medium text-gray-500">시작일</label>
                        <div className="flex h-9 w-full items-center rounded-md border border-gray-200 px-3 text-sm font-medium text-gray-700">
                          <CalendarDays className="mr-2 h-3.5 w-3.5 text-gray-400" />
                          {tempStartDate ? (
                            format(tempStartDate, "yyyy-MM-dd")
                          ) : (
                            <span className="text-gray-400">선택</span>
                          )}
                        </div>
                        <Calendar
                          mode="single"
                          selected={tempStartDate}
                          onSelect={setTempStartDate}
                          locale={ko}
                          className="mt-1.5 rounded-md border border-gray-100"
                        />
                      </div>
                      <div className="flex items-center pt-6">
                        <span className="text-sm text-gray-400">~</span>
                      </div>
                      <div className="flex-1">
                        <label className="mb-1.5 block text-xs font-medium text-gray-500">종료일</label>
                        <div className="flex h-9 w-full items-center rounded-md border border-gray-200 px-3 text-sm font-medium text-gray-700">
                          <CalendarDays className="mr-2 h-3.5 w-3.5 text-gray-400" />
                          {tempEndDate ? (
                            format(tempEndDate, "yyyy-MM-dd")
                          ) : (
                            <span className="text-gray-400">선택</span>
                          )}
                        </div>
                        <Calendar
                          mode="single"
                          selected={tempEndDate}
                          onSelect={setTempEndDate}
                          locale={ko}
                          className="mt-1.5 rounded-md border border-gray-100"
                        />
                      </div>
                    </div>

                    <Button
                      onClick={handleApplyDateFilter}
                      disabled={!tempStartDate || !tempEndDate}
                      className="h-9 w-full bg-blue-600 text-sm text-white hover:bg-blue-700"
                    >
                      적용
                    </Button>
                  </div>
                </div>
              )}
            </div>

            {isDateFilterActive && (
              <div className="flex items-center gap-1.5 rounded-lg border border-blue-200 bg-blue-50 px-3 py-1.5">
                <CalendarDays className="h-4 w-4 text-blue-600" />
                <span className="text-sm font-medium text-blue-700">
                  {startDate} ~ {endDate}
                </span>
                <button
                  onClick={handleClearDateFilter}
                  className="ml-1 rounded p-0.5 text-blue-400 transition-colors hover:bg-blue-100 hover:text-blue-600"
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            )}

            <div className="flex items-center overflow-hidden rounded-md border border-gray-200">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleViewModeChange("list")}
                className={`h-9 w-9 rounded-none ${viewMode === "list" ? "bg-gray-100" : ""}`}
                title="리스트 보기"
              >
                <List className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleViewModeChange("grid")}
                className={`h-9 w-9 rounded-none border-l ${viewMode === "grid" ? "bg-gray-100" : ""}`}
                title="그리드 보기"
              >
                <LayoutGrid className="h-4 w-4" />
              </Button>
            </div>

            <Button
              onClick={handleCreateNew}
              className="ml-auto h-9 gap-1.5 bg-blue-600 text-sm text-white hover:bg-blue-700"
            >
              <Plus className="h-4 w-4" />새 리포트
            </Button>
          </div>
        </div>
      </div>

      <div className="flex min-h-0 flex-1 flex-col gap-5 px-8 py-5">
        <div className="grid shrink-0 auto-rows-fr grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
          <div className="flex items-center justify-center gap-5 overflow-hidden rounded-xl border border-gray-100 bg-white px-6 py-8 transition-all hover:border-gray-200 hover:shadow-sm">
            <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-blue-50">
              <FileText className="h-8 w-8 text-blue-600" />
            </div>
            <div>
              <span className="text-lg font-bold whitespace-nowrap text-gray-500">전체 리포트</span>
              <p className="mt-1 text-5xl font-bold tracking-tight whitespace-nowrap text-gray-900 tabular-nums">
                {total.toLocaleString()}
                <span className="ml-1.5 text-xl font-bold text-gray-400">건</span>
              </p>
            </div>
          </div>

          <div className="relative flex items-center justify-center gap-8 rounded-xl border border-gray-100 bg-white px-6 py-8 transition-all hover:border-gray-200 hover:shadow-sm">
            <div className="flex items-center gap-5">
              <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-purple-50">
                <Users className="h-8 w-8 text-purple-600" />
              </div>
              <div>
                <span className="text-lg font-bold whitespace-nowrap text-gray-500">작성자</span>
                <p className="mt-1 text-5xl font-bold tracking-tight whitespace-nowrap text-gray-900 tabular-nums">
                  {authorCount.toLocaleString()}
                  <span className="ml-1.5 text-xl font-bold text-gray-400">명</span>
                </p>
              </div>
            </div>
            {authorStats.length > 0 && (
              <div className="h-[80px] w-[100px] shrink-0" style={{ overflow: "visible" }}>
                <BarChart width={100} height={80} data={authorStats} margin={{ top: 12, right: 0, bottom: 0, left: 0 }}>
                  <Bar
                    dataKey="count" fill="#a78bfa" radius={[3, 3, 0, 0]} maxBarSize={18}
                    isAnimationActive={true} animationDuration={1200} animationEasing="ease-out"
                  >
                    <LabelList dataKey="count" position="top" style={{ fontSize: "10px", fontWeight: 700, fill: "#6d28d9" }} />
                  </Bar>
                  <Tooltip
                    formatter={(value: number) => [`${value}건`, "리포트"]}
                    labelFormatter={(_label: any, payload: any) => payload?.[0]?.payload?.name || _label}
                    contentStyle={{ fontSize: "11px", borderRadius: "6px", boxShadow: "0 2px 8px rgba(0,0,0,0.12)" }}
                    wrapperStyle={{ zIndex: 50, pointerEvents: "none" }}
                    cursor={false}
                    allowEscapeViewBox={{ x: true, y: true }}
                  />
                </BarChart>
              </div>
            )}
          </div>

          <div className="flex flex-col items-center rounded-xl border border-gray-100 bg-white px-6 py-6 transition-all hover:border-gray-200 hover:shadow-sm">
            <span className="text-lg font-bold whitespace-nowrap text-gray-500">
              최근 30일 활동{" "}
              <span className="text-base font-semibold text-gray-400 tabular-nums">
                ({recentTotal.toLocaleString()}건)
              </span>
            </span>
            <div className="mt-2 flex w-full flex-1 items-center justify-center">
              <div className="shrink-0" style={{ overflow: "visible" }}>
                <BarChart
                  width={220} height={100} data={recentActivity}
                  barCategoryGap="12%" margin={{ top: 16, right: 2, bottom: 0, left: 2 }}
                >
                  <XAxis dataKey="date" tick={{ fontSize: 12, fill: "#374151", fontWeight: 700 }} axisLine={false} tickLine={false} />
                  <Bar
                    dataKey="count" fill="#60a5fa" radius={[4, 4, 0, 0]} maxBarSize={32}
                    isAnimationActive={true} animationDuration={1200} animationEasing="ease-out"
                  />
                  <Tooltip
                    formatter={(value: number) => [`${value}건`, "수정"]}
                    contentStyle={{ fontSize: "12px", borderRadius: "6px", boxShadow: "0 2px 8px rgba(0,0,0,0.12)" }}
                    cursor={false}
                    allowEscapeViewBox={{ x: true, y: true }}
                  />
                </BarChart>
              </div>
            </div>
          </div>

          <div className="flex flex-col items-center rounded-xl border border-gray-100 bg-white px-6 py-6 transition-all hover:border-gray-200 hover:shadow-sm">
            <span className="text-lg font-bold whitespace-nowrap text-gray-500">카테고리별 분포</span>
            <div className="flex flex-1 items-center justify-center">
              {typeData.length === 0 ? (
                <p className="text-lg font-bold text-gray-400">데이터 없음</p>
              ) : (
                <div className="flex flex-col items-center gap-2.5">
                  <div className="shrink-0" style={{ overflow: "visible", position: "relative" }}>
                    <PieChart width={90} height={90} style={{ overflow: "visible" }}>
                      <Pie
                        data={typeData} cx="50%" cy="50%" innerRadius={20} outerRadius={40}
                        dataKey="value" nameKey="type" startAngle={90} endAngle={-270}
                        strokeWidth={2} stroke="#fff"
                        isAnimationActive={true} animationDuration={1200} animationEasing="ease-out"
                      >
                        {typeData.map((entry) => (
                          <Cell key={entry.type} fill={REPORT_TYPE_COLORS[getTypeColorIndex(entry.type) % REPORT_TYPE_COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip
                        formatter={(value: number, name: string) => [`${value}건`, getTypeLabel(name)]}
                        contentStyle={{ fontSize: "12px", borderRadius: "6px", boxShadow: "0 2px 8px rgba(0,0,0,0.12)" }}
                        wrapperStyle={{ zIndex: 20, pointerEvents: "none" }}
                        allowEscapeViewBox={{ x: true, y: true }}
                      />
                    </PieChart>
                  </div>
                  <div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1">
                    {typeData.slice(0, 4).map((entry) => {
                      const TypeIcon = getTypeIcon(entry.type);
                      return (
                        <div key={entry.type} className="flex items-center gap-1.5">
                          <div
                            className="flex h-4 w-4 shrink-0 items-center justify-center rounded"
                            style={{ backgroundColor: REPORT_TYPE_COLORS[getTypeColorIndex(entry.type) % REPORT_TYPE_COLORS.length] }}
                          >
                            <TypeIcon className="h-2.5 w-2.5 text-white" strokeWidth={2.5} />
                          </div>
                          <span className="text-sm font-medium whitespace-nowrap text-gray-600">{getTypeLabel(entry.type)}</span>
                          <span className="text-sm font-bold whitespace-nowrap text-gray-900">{entry.value}</span>
                        </div>
                      );
                    })}
                    {typeData.length > 4 && <span className="text-xs text-gray-400">외 {typeData.length - 4}개</span>}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-gray-200 bg-white">
          <div className="flex shrink-0 items-center justify-between border-b border-gray-200 bg-gray-50/50 px-5 py-3">
            <span className="flex items-center gap-2.5 text-base font-semibold text-gray-900">
              리포트 목록
              <span className="text-sm font-normal text-gray-400">(총 {total}건)</span>
            </span>
          </div>
          <div className="min-h-0 flex-1 overflow-auto">
            <ReportListTable
              reports={reports}
              total={total}
              page={page}
              limit={limit}
              isLoading={isLoading}
              viewMode={viewMode}
              onPageChange={setPage}
              onRefresh={refetch}
              onViewClick={setViewTarget}
              onCopyClick={setCopyTarget}
            />
          </div>
        </div>
      </div>

      <ReportCreateModal isOpen={isCreateOpen} onClose={() => setIsCreateOpen(false)} onSuccess={refetch} />

      <ReportListPreviewModal report={viewTarget} onClose={() => setViewTarget(null)} />

      {copyTarget && (
        <ReportCopyModal
          report={copyTarget}
          onClose={() => setCopyTarget(null)}
          onSuccess={() => {
            setCopyTarget(null);
            refetch();
          }}
        />
      )}
    </div>
  );
}
