'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import {
  Clock,
  UserCheck,
  AlertCircle,
  Calendar,
  Download,
  Plus,
  FileText,
  Edit,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { format } from 'date-fns';
import { ko } from 'date-fns/locale';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type StatCard,
  type TabOption,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { AttendanceInfoDialog } from './AttendanceInfoDialog';
import { ReasonInfoDialog } from './ReasonInfoDialog';
import type {
  AttendanceRecord,
  AttendanceStatus,
  SortOption,
  FilterOption,
  AttendanceFormData,
  ReasonFormData,
} from './types';
import {
  ATTENDANCE_STATUS_LABELS,
  ATTENDANCE_STATUS_COLORS,
  SORT_OPTIONS,
  FILTER_OPTIONS,
  REASON_TYPE_LABELS,
} from './types';

/**
 * Mock 데이터 - 실제 API 연동 전 테스트용
 */
const mockEmployees = [
  { id: '1', name: '이름', department: '부서명', position: '부서장팀장', rank: '부장' },
  { id: '2', name: '이름', department: '부서명', position: '팀장', rank: '부장' },
  { id: '3', name: '이름', department: '부서명', position: '부서장팀장', rank: '부장' },
  { id: '4', name: '이름', department: '부서명', position: '팀장', rank: '부장' },
  { id: '5', name: '이름', department: '부서명', position: '부서장팀장', rank: '부장' },
  { id: '6', name: '이름', department: '부서명', position: '팀장', rank: '부장' },
  { id: '7', name: '이름', department: '부서명', position: '부서장팀장', rank: '부장' },
];

// Mock 근태 기록 생성
const generateMockAttendanceRecords = (): AttendanceRecord[] => {
  const records: AttendanceRecord[] = [];
  const statuses: AttendanceStatus[] = ['onTime', 'onTime', 'onTime', 'late', 'absent', 'vacation', 'onTime'];
  const reasons = [
    null,
    null,
    null,
    null,
    { type: 'businessTripRequest' as const, label: '출장기안', documentId: 'doc1' },
    { type: 'fieldWorkRequest' as const, label: '외근승인', documentId: 'doc2' },
    null,
  ];

  mockEmployees.forEach((employee, index) => {
    records.push({
      id: String(index + 1),
      employeeId: employee.id,
      employeeName: employee.name,
      department: employee.department,
      position: employee.position,
      rank: employee.rank,
      baseDate: '2025-09-03',
      checkIn: index === 4 ? null : '08:40',
      checkOut: index === 4 ? null : '21:40',
      breakTime: '1시간',
      overtimeHours: index % 2 === 0 ? '3시간 30분' : '1시간',
      reason: reasons[index],
      status: statuses[index],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    });
  });

  return records;
};

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

  // 근태 데이터 상태
  const [attendanceRecords, setAttendanceRecords] = useState<AttendanceRecord[]>(generateMockAttendanceRecords);

  // 검색 및 필터 상태
  const [searchValue, setSearchValue] = useState('');
  const [activeTab, setActiveTab] = useState<string>('all');
  const [filterOption, setFilterOption] = useState<FilterOption>('all');
  const [sortOption, setSortOption] = useState<SortOption>('rank');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태 (Input type="date" 용)
  const [startDate, setStartDate] = useState('2025-09-01');
  const [endDate, setEndDate] = useState('2025-09-03');

  // 다이얼로그 상태
  const [attendanceDialogOpen, setAttendanceDialogOpen] = useState(false);
  const [attendanceDialogMode, setAttendanceDialogMode] = useState<'create' | 'edit'>('create');
  const [selectedAttendance, setSelectedAttendance] = useState<AttendanceRecord | null>(null);
  const [reasonDialogOpen, setReasonDialogOpen] = useState(false);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  // 필터링된 데이터
  const filteredRecords = useMemo(() => {
    let filtered = attendanceRecords;

    // 탭(상태) 필터
    if (activeTab !== 'all') {
      filtered = filtered.filter(r => r.status === activeTab);
    }

    // 상단 필터 드롭다운 (탭과 별개)
    if (filterOption !== 'all') {
      filtered = filtered.filter(r => r.status === filterOption);
    }

    // 검색 필터
    if (searchValue) {
      const search = searchValue.toLowerCase();
      filtered = filtered.filter(r =>
        r.employeeName.toLowerCase().includes(search) ||
        r.department.toLowerCase().includes(search)
      );
    }

    // 정렬
    filtered = [...filtered].sort((a, b) => {
      switch (sortOption) {
        case 'rank':
          return a.rank.localeCompare(b.rank, 'ko');
        case 'deptAsc':
          return a.department.localeCompare(b.department, 'ko');
        case 'deptDesc':
          return b.department.localeCompare(a.department, 'ko');
        case 'nameAsc':
          return a.employeeName.localeCompare(b.employeeName, 'ko');
        case 'nameDesc':
          return b.employeeName.localeCompare(a.employeeName, 'ko');
        default:
          return 0;
      }
    });

    return filtered;
  }, [attendanceRecords, activeTab, filterOption, searchValue, sortOption]);

  // 페이지네이션된 데이터
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredRecords.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredRecords, currentPage, itemsPerPage]);

  // 통계 계산
  const stats = useMemo(() => {
    const onTimeCount = attendanceRecords.filter(r => r.status === 'onTime').length;
    const lateCount = attendanceRecords.filter(r => r.status === 'late').length;
    const absentCount = attendanceRecords.filter(r => r.status === 'absent').length;
    const vacationCount = attendanceRecords.filter(r => r.status === 'vacation').length;

    return { onTimeCount, lateCount, absentCount, vacationCount };
  }, [attendanceRecords]);

  // StatCards 데이터
  const statCards: StatCard[] = useMemo(() => [
    {
      label: '정시 출근',
      value: `${stats.onTimeCount}명`,
      icon: UserCheck,
      iconColor: 'text-green-500',
    },
    {
      label: '지각',
      value: `${stats.lateCount}명`,
      icon: Clock,
      iconColor: 'text-yellow-500',
    },
    {
      label: '결근',
      value: `${stats.absentCount}명`,
      icon: AlertCircle,
      iconColor: 'text-red-500',
    },
    {
      label: '휴가',
      value: `${stats.vacationCount}명`,
      icon: Calendar,
      iconColor: 'text-blue-500',
    },
  ], [stats]);

  // 탭 옵션
  const tabs: TabOption[] = useMemo(() => [
    { value: 'all', label: '전체', count: attendanceRecords.length, color: 'gray' },
    { value: 'onTime', label: '정시 출근', count: stats.onTimeCount, color: 'green' },
    { value: 'late', label: '지각', count: stats.lateCount, color: 'yellow' },
    { value: 'absent', label: '결근', count: stats.absentCount, color: 'red' },
    { value: 'vacation', label: '휴가', count: stats.vacationCount, color: 'blue' },
    { value: 'businessTrip', label: '출장', count: attendanceRecords.filter(r => r.status === 'businessTrip').length, color: 'purple' },
    { value: 'fieldWork', label: '외근', count: attendanceRecords.filter(r => r.status === 'fieldWork').length, color: 'orange' },
    { value: 'overtime', label: '연장근무', count: attendanceRecords.filter(r => r.status === 'overtime').length, color: 'indigo' },
  ], [attendanceRecords.length, stats]);

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'department', label: '부서', className: 'min-w-[80px]' },
    { key: 'position', label: '직책', className: 'min-w-[100px]' },
    { key: 'name', label: '이름', className: 'min-w-[60px]' },
    { key: 'rank', label: '직급', className: 'min-w-[60px]' },
    { key: 'baseDate', label: '기준일', className: 'min-w-[100px]' },
    { key: 'checkIn', label: '출근', className: 'min-w-[60px]' },
    { key: 'checkOut', label: '퇴근', className: 'min-w-[60px]' },
    { key: 'breakTime', label: '휴게', className: 'min-w-[60px]' },
    { key: 'overtime', label: '연장근무', className: 'min-w-[80px]' },
    { key: 'reason', label: '사유', className: 'min-w-[80px]' },
    { key: 'actions', label: '작업', className: 'w-[60px] text-center' },
  ], []);

  // 체크박스 토글
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  // 전체 선택/해제
  const toggleSelectAll = useCallback(() => {
    if (selectedItems.size === paginatedData.length && paginatedData.length > 0) {
      setSelectedItems(new Set());
    } else {
      const allIds = new Set(paginatedData.map((item) => item.id));
      setSelectedItems(allIds);
    }
  }, [selectedItems.size, paginatedData]);

  // 핸들러
  const handleAddAttendance = useCallback(() => {
    setAttendanceDialogMode('create');
    setSelectedAttendance(null);
    setAttendanceDialogOpen(true);
  }, []);

  const handleAddReason = useCallback(() => {
    setReasonDialogOpen(true);
  }, []);

  const handleEditAttendance = useCallback((record: AttendanceRecord) => {
    setAttendanceDialogMode('edit');
    setSelectedAttendance(record);
    setAttendanceDialogOpen(true);
  }, []);

  const handleSaveAttendance = useCallback((data: AttendanceFormData) => {
    console.log('Save attendance:', data);
    // TODO: API 연동
    setAttendanceDialogOpen(false);
  }, []);

  const handleSubmitReason = useCallback((data: ReasonFormData) => {
    console.log('Submit reason:', data);
    // TODO: 문서 작성 화면으로 이동
    router.push(`/ko/hr/documents/new?type=${data.reasonType}`);
  }, [router]);

  const handleExcelDownload = useCallback(() => {
    console.log('Excel download');
    // TODO: 엑셀 다운로드 기능 구현
  }, []);

  const handleReasonClick = useCallback((record: AttendanceRecord) => {
    if (record.reason?.documentId) {
      router.push(`/ko/hr/documents/${record.reason.documentId}`);
    }
  }, [router]);

  // 테이블 행 렌더링
  const renderTableRow = useCallback((item: AttendanceRecord, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50"
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(item.id)}
          />
        </TableCell>
        <TableCell className="text-center">{globalIndex}</TableCell>
        <TableCell>{item.department}</TableCell>
        <TableCell>{item.position}</TableCell>
        <TableCell>{item.employeeName}</TableCell>
        <TableCell>{item.rank}</TableCell>
        <TableCell>
          {item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd (E)', { locale: ko }) : '-'}
        </TableCell>
        <TableCell>{item.checkIn || '-'}</TableCell>
        <TableCell>{item.checkOut || '-'}</TableCell>
        <TableCell>{item.breakTime || '-'}</TableCell>
        <TableCell>{item.overtimeHours || '-'}</TableCell>
        <TableCell>
          {item.reason ? (
            <Button
              variant="link"
              size="sm"
              className="p-0 h-auto text-blue-600 hover:text-blue-800"
              onClick={() => handleReasonClick(item)}
            >
              {item.reason.label}
            </Button>
          ) : '-'}
        </TableCell>
        <TableCell className="text-center">
          {isSelected && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEditAttendance(item)}
              title="수정"
            >
              <Edit className="w-4 h-4" />
            </Button>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleEditAttendance, handleReasonClick]);

  // 모바일 카드 렌더링
  const renderMobileCard = useCallback((
    item: AttendanceRecord,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.employeeName}
        headerBadges={
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="text-xs">
              {item.department}
            </Badge>
            <Badge variant="outline" className="text-xs">
              {item.rank}
            </Badge>
          </div>
        }
        statusBadge={
          <Badge className={ATTENDANCE_STATUS_COLORS[item.status]}>
            {ATTENDANCE_STATUS_LABELS[item.status]}
          </Badge>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="직책" value={item.position} />
            <InfoField
              label="기준일"
              value={item.baseDate ? format(new Date(item.baseDate), 'yyyy-MM-dd') : '-'}
            />
            <InfoField label="출근" value={item.checkIn || '-'} />
            <InfoField label="퇴근" value={item.checkOut || '-'} />
            <InfoField label="휴게" value={item.breakTime || '-'} />
            <InfoField label="연장근무" value={item.overtimeHours || '-'} />
            {item.reason && (
              <InfoField label="사유" value={item.reason.label} />
            )}
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleEditAttendance(item); }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
            </div>
          ) : undefined
        }
      />
    );
  }, [handleEditAttendance]);

  // 헤더 액션 (DateRangeSelector + 버튼들)
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <div className="ml-auto flex gap-2">
        <Button variant="outline" onClick={handleExcelDownload}>
          <Download className="w-4 h-4 mr-2" />
          엑셀 다운로드
        </Button>
        <Button onClick={handleAddAttendance}>
          <Plus className="w-4 h-4 mr-2" />
          근태 등록
        </Button>
      </div>
    </>
  );

  // 테이블 헤더 액션 (필터 + 정렬 셀렉트) - 사원관리와 동일한 위치
  const tableHeaderActions = (
    <div className="flex items-center gap-2">
      {/* 필터 셀렉트박스 */}
      <Select value={filterOption} onValueChange={(value) => setFilterOption(value as FilterOption)}>
        <SelectTrigger className="w-[140px]">
          <SelectValue placeholder="필터 선택" />
        </SelectTrigger>
        <SelectContent>
          {FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 정렬 셀렉트박스 */}
      <Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
        <SelectTrigger className="w-[140px]">
          <SelectValue placeholder="정렬 선택" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  // 검색 옆 추가 필터 (사유 등록 버튼)
  const extraFilters = (
    <div className="flex items-center gap-2 flex-wrap">
      <Button variant="outline" onClick={handleAddReason}>
        <FileText className="w-4 h-4 mr-2" />
        사유 등록
      </Button>
    </div>
  );

  // 페이지네이션 설정
  const totalPages = Math.ceil(filteredRecords.length / itemsPerPage);

  return (
    <>
      <IntegratedListTemplateV2<AttendanceRecord>
        title="근태관리"
        description="직원 출퇴근 및 근태 정보를 관리합니다"
        icon={Clock}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        searchPlaceholder="이름, 부서 검색..."
        extraFilters={extraFilters}
        tableHeaderActions={tableHeaderActions}
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredRecords.length}
        allData={filteredRecords}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredRecords.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 근태 정보 다이얼로그 */}
      <AttendanceInfoDialog
        open={attendanceDialogOpen}
        onOpenChange={setAttendanceDialogOpen}
        mode={attendanceDialogMode}
        attendance={selectedAttendance}
        employees={mockEmployees}
        onSave={handleSaveAttendance}
      />

      {/* 사유 정보 다이얼로그 */}
      <ReasonInfoDialog
        open={reasonDialogOpen}
        onOpenChange={setReasonDialogOpen}
        employees={mockEmployees}
        onSubmit={handleSubmitReason}
      />
    </>
  );
}