"use client";

import React from "react";
import { ChartConfig } from "./types";
import { Card } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Calendar, ChevronDown, ChevronUp } from "lucide-react";
import { getQuickDateRange } from "./utils/queryHelpers";

interface DateFilterPanelProps {
  config: ChartConfig;
  dateColumns: string[];
  onChange: (updates: Partial<ChartConfig>) => void;
}

export function DateFilterPanel({ config, dateColumns, onChange }: DateFilterPanelProps) {
  const [isExpanded, setIsExpanded] = React.useState(false);

  const dateFilter = config.dateFilter || {
    enabled: false,
    dateColumn: dateColumns[0] || "",
    startDate: "",
    endDate: "",
  };

  const handleQuickRange = (range: "today" | "week" | "month" | "year") => {
    const { startDate, endDate } = getQuickDateRange(range);
    onChange({
      dateFilter: {
        ...dateFilter,
        enabled: true,
        startDate,
        endDate,
        quickRange: range,
      },
    });
  };

  // 날짜 컬럼이 없으면 표시하지 않음
  if (dateColumns.length === 0) {
    return null;
  }

  return (
    <Card className="p-4">
      <div className="flex cursor-pointer items-center justify-between" onClick={() => setIsExpanded(!isExpanded)}>
        <div className="flex items-center gap-2">
          <Calendar className="h-4 w-4 text-primary" />
          <Label className="cursor-pointer text-sm font-medium text-foreground">데이터 필터 (선택)</Label>
          {dateFilter.enabled && <span className="rounded bg-primary/10 px-2 py-0.5 text-xs text-primary">활성</span>}
        </div>
        {isExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
      </div>

      {isExpanded && (
        <div className="mt-4 space-y-4">
          {/* 필터 활성화 */}
          <div className="flex items-center gap-2">
            <Checkbox
              id="enableDateFilter"
              checked={dateFilter.enabled}
              onCheckedChange={(checked) =>
                onChange({
                  dateFilter: {
                    ...dateFilter,
                    enabled: checked as boolean,
                  },
                })
              }
            />
            <Label htmlFor="enableDateFilter" className="cursor-pointer text-sm font-normal">
              날짜 필터 사용
            </Label>
          </div>

          {dateFilter.enabled && (
            <>
              {/* 날짜 컬럼 선택 */}
              <div>
                <Label className="mb-2 text-sm font-medium text-foreground">날짜 컬럼</Label>
                <Select
                  value={dateFilter.dateColumn || ""}
                  onValueChange={(value) =>
                    onChange({
                      dateFilter: {
                        ...dateFilter,
                        dateColumn: value,
                      },
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="날짜 컬럼 선택" />
                  </SelectTrigger>
                  <SelectContent className="z-[99999]">
                    {dateColumns.map((col) => (
                      <SelectItem key={col} value={col}>
                        {col}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="mt-1 text-xs text-muted-foreground">감지된 날짜 컬럼: {dateColumns.join(", ")}</p>
              </div>

              {/* 빠른 선택 */}
              <div>
                <Label className="mb-2 text-sm font-medium text-foreground">빠른 선택</Label>
                <div className="flex flex-wrap gap-2">
                  <Button
                    type="button"
                    variant={dateFilter.quickRange === "today" ? "default" : "outline"}
                    size="sm"
                    onClick={() => handleQuickRange("today")}
                  >
                    오늘
                  </Button>
                  <Button
                    type="button"
                    variant={dateFilter.quickRange === "week" ? "default" : "outline"}
                    size="sm"
                    onClick={() => handleQuickRange("week")}
                  >
                    이번 주
                  </Button>
                  <Button
                    type="button"
                    variant={dateFilter.quickRange === "month" ? "default" : "outline"}
                    size="sm"
                    onClick={() => handleQuickRange("month")}
                  >
                    이번 달
                  </Button>
                  <Button
                    type="button"
                    variant={dateFilter.quickRange === "year" ? "default" : "outline"}
                    size="sm"
                    onClick={() => handleQuickRange("year")}
                  >
                    올해
                  </Button>
                </div>
              </div>

              {/* 직접 입력 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="mb-2 text-sm font-medium text-foreground">시작일</Label>
                  <Input
                    type="date"
                    value={dateFilter.startDate || ""}
                    onChange={(e) =>
                      onChange({
                        dateFilter: {
                          ...dateFilter,
                          startDate: e.target.value,
                          quickRange: undefined, // 직접 입력 시 빠른 선택 해제
                        },
                      })
                    }
                  />
                </div>
                <div>
                  <Label className="mb-2 text-sm font-medium text-foreground">종료일</Label>
                  <Input
                    type="date"
                    value={dateFilter.endDate || ""}
                    onChange={(e) =>
                      onChange({
                        dateFilter: {
                          ...dateFilter,
                          endDate: e.target.value,
                          quickRange: undefined, // 직접 입력 시 빠른 선택 해제
                        },
                      })
                    }
                  />
                </div>
              </div>

              {/* 필터 정보 */}
              {dateFilter.startDate && dateFilter.endDate && (
                <div className="rounded-md bg-primary/10 p-3 text-sm text-primary">
                  <strong>필터 적용:</strong> {dateFilter.dateColumn} 컬럼에서 {dateFilter.startDate}부터{" "}
                  {dateFilter.endDate}까지 데이터를 가져옵니다.
                </div>
              )}
            </>
          )}
        </div>
      )}
    </Card>
  );
}
