'use client';

/**
 * 제품검사 목록
 *
 * 기획서 기반 전면 재구축:
 * - DateRangeSelector (기간 필터)
 * - 통계 카드 3개 (접수/진행중/완료)
 * - 테이블 (11개 컬럼)
 * - 하단 제품검사 스케줄 캘린더 (주/월 뷰)
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useStatsLoader } from '@/hooks/useStatsLoader';
import {
  ClipboardCheck,
  Plus,
  FileInput,
  Loader2,
  CheckCircle2,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { ScheduleCalendar } from '@/components/common/ScheduleCalendar/ScheduleCalendar';
import type { ScheduleEvent, CalendarView } from '@/components/common/ScheduleCalendar/types';
import { getInspections, getInspectionStats, getInspectionCalendar } from './actions';
import { statusColorMap } from './mockData';
import { parseISO } from 'date-fns';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { getLocalDateString } from '@/lib/utils/date';
import type { ProductInspection, InspectionStatus } from './types';

const ITEMS_PER_PAGE = 20;

export function InspectionList() {
  const router = useRouter();

  // ===== 날짜 범위 =====
  const today = new Date();
  const [startDate, setStartDate] = useState(() => {
    const d = new Date(today.getFullYear(), today.getMonth(), 1);
    return getLocalDateString(d);
  });
  const [endDate, setEndDate] = useState(() => {
    const d = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    return getLocalDateString(d);
  });

  // ===== 통계 (목록과 동일 날짜 범위 적용) =====
  const { data: statsData, reload: reloadStats } = useStatsLoader(
    useCallback(() => getInspectionStats({ dateFrom: startDate, dateTo: endDate }), [startDate, endDate])
  );

  // ===== 캘린더 상태 =====
  const [calendarDate, setCalendarDate] = useState(new Date());
  const [scheduleView, setScheduleView] = useState<CalendarView>('month');
  const [calendarEvents, setCalendarEvents] = useState<ScheduleEvent[]>([]);
  const [calendarStatusFilter, setCalendarStatusFilter] = useState<string>('전체');
  const [calendarInspectorFilter, setCalendarInspectorFilter] = useState<string>('전체');

  // startDate 변경 시 캘린더 월 자동 이동
  useEffect(() => {
    if (startDate) {
      const parsed = parseISO(startDate);
      if (!isNaN(parsed.getTime())) {
        setCalendarDate(parsed);
      }
    }
  }, [startDate]);

  // 캘린더 데이터 로드
  const loadCalendarData = useCallback(async () => {
    try {
      const year = calendarDate.getFullYear();
      const month = calendarDate.getMonth() + 1;
      const result = await getInspectionCalendar({
        year,
        month,
        status: calendarStatusFilter !== '전체' ? calendarStatusFilter as InspectionStatus : undefined,
        inspector: calendarInspectorFilter !== '전체' ? calendarInspectorFilter : undefined,
      });

      if (result.success) {
        const events: ScheduleEvent[] = result.data.map((item) => {
          const statusColorMap: Record<string, string> = {
            접수: 'blue',
            진행중: 'indigo',
            완료: 'blue',
          };
          return {
            id: item.id,
            title: `${item.inspector} – ${item.siteName} / ${item.status}`,
            startDate: item.startDate,
            endDate: item.endDate,
            color: statusColorMap[item.status] || 'blue',
            status: item.status,
            data: item,
          };
        });
        setCalendarEvents(events);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[InspectionList] loadCalendarData error:', error);
    }
  }, [calendarDate, calendarStatusFilter, calendarInspectorFilter]);

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

  // ===== 행 클릭 =====
  const handleRowClick = useCallback(
    (item: ProductInspection) => {
      router.push(`/quality/inspections/${item.id}?mode=view`);
    },
    [router]
  );

  // ===== 등록 =====
  const handleCreate = useCallback(() => {
    router.push('/quality/inspections?mode=new');
  }, [router]);

  // ===== 캘린더 핸들러 =====
  const handleCalendarEventClick = useCallback((event: ScheduleEvent) => {
    if (event.data && typeof event.data === 'object' && 'id' in event.data) {
      const item = event.data as { id: string };
      router.push(`/quality/inspections/${item.id}?mode=view`);
    }
  }, [router]);

  const handleCalendarDateClick = useCallback((date: Date) => {
    setCalendarDate(date);
  }, []);

  // ===== 통계 카드 (3개: 접수/진행중/완료) =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '접수',
        value: statsData?.receptionCount ?? 0,
        icon: FileInput,
        iconColor: 'text-gray-600',
      },
      {
        label: '진행중',
        value: statsData?.inProgressCount ?? 0,
        icon: Loader2,
        iconColor: 'text-blue-600',
      },
      {
        label: '완료',
        value: statsData?.completedCount ?? 0,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
    ],
    [statsData]
  );

  // ===== 캘린더 필터 슬롯 =====
  const calendarFilterSlot = useMemo(
    () => (
      <div className="flex items-center gap-2">
        <Select value={calendarStatusFilter} onValueChange={setCalendarStatusFilter}>
          <SelectTrigger className="min-w-[100px] w-auto h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="전체">전체</SelectItem>
            <SelectItem value="접수">접수</SelectItem>
            <SelectItem value="진행중">진행중</SelectItem>
            <SelectItem value="완료">완료</SelectItem>
          </SelectContent>
        </Select>
        <Select value={calendarInspectorFilter} onValueChange={setCalendarInspectorFilter}>
          <SelectTrigger className="min-w-[100px] w-auto h-8 text-xs">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="전체">전체</SelectItem>
          </SelectContent>
        </Select>
      </div>
    ),
    [calendarStatusFilter, calendarInspectorFilter]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<ProductInspection> = useMemo(
    () => ({
      title: '제품검사 목록',
      description: '제품검사를 관리합니다',
      icon: ClipboardCheck,
      basePath: '/quality/inspections',

      idField: 'id',

      // API 액션
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getInspections({
              page: params?.page || 1,
              size: params?.pageSize || ITEMS_PER_PAGE,
              q: params?.search || undefined,
              dateFrom: startDate,
              dateTo: endDate,
            });

            if (result.success) {
              // 통계 재로드
              await reloadStats();

              return {
                success: true,
                data: result.data,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: result.error };
          } catch (error) {
            if (isNextRedirectError(error)) throw error;
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 날짜 범위 선택기
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 등록 버튼
      createButton: {
        label: '제품검사 등록',
        onClick: handleCreate,
        icon: Plus,
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: 'No.', className: 'w-[50px] text-center' },
        { key: 'qualityDocNumber', label: '품질관리서 번호', className: 'min-w-[120px]', copyable: true },
        { key: 'siteName', label: '현장명', className: 'min-w-[100px]', copyable: true },
        { key: 'client', label: '수주처', className: 'min-w-[80px]', copyable: true },
        { key: 'locationCount', label: '개소', className: 'w-[60px] text-center', copyable: true },
        { key: 'requiredInfo', label: '필수정보', className: 'w-[90px] text-center', copyable: true },
        { key: 'inspectionPeriod', label: '검사기간', className: 'min-w-[140px]', copyable: true },
        { key: 'inspector', label: '검사자', className: 'w-[80px] text-center', copyable: true },
        { key: 'status', label: '상태', className: 'w-[70px] text-center' },
        { key: 'author', label: '작성자', className: 'w-[80px] text-center', copyable: true },
        { key: 'receptionDate', label: '접수일', className: 'w-[100px] text-center', copyable: true },
      ],

      // 서버 사이드 페이지네이션
      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,

      // 검색
      searchPlaceholder: '품질관리서 번호, 현장명, 수주처 검색...',

      // 통계 카드
      stats,

      // 테이블 행 렌더링
      renderTableRow: (
        item: ProductInspection,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ProductInspection>
      ) => {
        return (
          <TableRow
            key={item.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleRowClick(item)}
          >
            <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
              <Checkbox
                checked={handlers.isSelected}
                onCheckedChange={handlers.onToggle}
              />
            </TableCell>
            <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell className="font-medium">{item.qualityDocNumber}</TableCell>
            <TableCell>{item.siteName}</TableCell>
            <TableCell>{item.client}</TableCell>
            <TableCell className="text-center">{item.locationCount}</TableCell>
            <TableCell className="text-center">
              {item.requiredInfo === '완료' ? (
                <Badge variant="outline" className={`text-xs ${getPresetStyle('success')}`}>완료</Badge>
              ) : (
                <Badge variant="outline" className={`text-xs ${getPresetStyle('destructive')}`}>{item.requiredInfo}</Badge>
              )}
            </TableCell>
            <TableCell>{item.inspectionPeriod}</TableCell>
            <TableCell className="text-center">{item.inspector || '-'}</TableCell>
            <TableCell className="text-center">
              <Badge className={`text-xs ${statusColorMap[item.status]} border-0`}>
                {item.status}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.author || '-'}</TableCell>
            <TableCell className="text-center">{item.receptionDate}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: ProductInspection,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<ProductInspection>
      ) => {
        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            headerBadges={
              <>
                <Badge variant="outline" className="text-xs">{globalIndex}</Badge>
                <Badge variant="outline" className="text-xs">{item.qualityDocNumber}</Badge>
              </>
            }
            title={item.siteName}
            statusBadge={
              <Badge className={`text-xs ${statusColorMap[item.status]} border-0`}>
                {item.status}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="수주처" value={item.client} />
                <InfoField label="개소" value={String(item.locationCount)} />
                <InfoField label="검사기간" value={item.inspectionPeriod} />
                <InfoField label="검사자" value={item.inspector || '-'} />
                <InfoField label="작성자" value={item.author || '-'} />
                <InfoField label="접수일" value={item.receptionDate} />
              </div>
            }
          />
        );
      },

      // 하단 캘린더
      afterTableContent: (
        <ScheduleCalendar
          events={calendarEvents}
          currentDate={calendarDate}
          view={scheduleView}
          onDateClick={handleCalendarDateClick}
          onEventClick={handleCalendarEventClick}
          onMonthChange={setCalendarDate}
          onViewChange={setScheduleView}
          titleSlot="제품검사 스케줄"
          filterSlot={calendarFilterSlot}
          weekStartsOn={0}
          availableViews={[
            { value: 'week', label: '주' },
            { value: 'month', label: '월' },
          ]}
        />
      ),
    }),
    [stats, startDate, endDate, calendarEvents, calendarDate, scheduleView, calendarFilterSlot, handleRowClick, handleCreate, handleCalendarDateClick, handleCalendarEventClick]
  );

  return <UniversalListPage config={config} />;
}
