'use client';

import { useState, useMemo, useCallback } from 'react';
import { format } from 'date-fns';
import {
  Download,
  DollarSign,
  Check,
  Clock,
  Pencil,
  Banknote,
  Briefcase,
  Timer,
  Gift,
  MinusCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type StatCard,
  type TabOption,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { SalaryDetailDialog } from './SalaryDetailDialog';
import type {
  SalaryRecord,
  SalaryDetail,
  PaymentStatus,
  SortOption,
} from './types';
import {
  PAYMENT_STATUS_LABELS,
  PAYMENT_STATUS_COLORS,
  SORT_OPTIONS,
  formatCurrency,
} from './types';

// ===== Mock 데이터 생성 =====
const generateSalaryData = (): SalaryRecord[] => {
  const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
  const positions = ['팀장', '파트장', '선임', '주임', '사원'];
  const ranks = ['부장', '차장', '과장', '대리', '사원'];
  const statuses: PaymentStatus[] = ['scheduled', 'completed'];
  const names = ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'];

  return Array.from({ length: 10 }, (_, i) => {
    const baseSalary = 3000000 + Math.floor(Math.random() * 2000000);
    const allowance = 300000 + Math.floor(Math.random() * 500000);
    const overtime = Math.floor(Math.random() * 500000);
    const bonus = Math.floor(Math.random() * 1000000);
    const deduction = 200000 + Math.floor(Math.random() * 300000);
    const netPayment = baseSalary + allowance + overtime + bonus - deduction;

    return {
      id: `salary-${i + 1}`,
      employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
      employeeName: names[i],
      department: departments[i % departments.length],
      position: positions[i % positions.length],
      rank: ranks[i % ranks.length],
      baseSalary,
      allowance,
      overtime,
      bonus,
      deduction,
      netPayment,
      paymentDate: format(new Date(2025, 11, 25), 'yyyy-MM-dd'),
      status: statuses[i % statuses.length],
      year: 2025,
      month: 12,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  });
};

// Mock 상세 데이터 생성
const generateSalaryDetail = (record: SalaryRecord): SalaryDetail => {
  const positionAllowance = 100000 + Math.floor(Math.random() * 200000);
  const overtimeAllowance = Math.floor(Math.random() * 300000);
  const mealAllowance = 100000;
  const transportAllowance = 100000;
  const otherAllowance = Math.floor(Math.random() * 100000);

  const totalAllowance = positionAllowance + overtimeAllowance + mealAllowance + transportAllowance + otherAllowance;

  const nationalPension = Math.floor(record.baseSalary * 0.045);
  const healthInsurance = Math.floor(record.baseSalary * 0.0343);
  const longTermCare = Math.floor(healthInsurance * 0.1227);
  const employmentInsurance = Math.floor(record.baseSalary * 0.009);
  const incomeTax = Math.floor((record.baseSalary + totalAllowance) * 0.08);
  const localIncomeTax = Math.floor(incomeTax * 0.1);
  const otherDeduction = Math.floor(Math.random() * 50000);

  const totalDeduction = nationalPension + healthInsurance + longTermCare + employmentInsurance + incomeTax + localIncomeTax + otherDeduction;

  return {
    employeeId: record.employeeId,
    employeeName: record.employeeName,
    department: record.department,
    position: record.position,
    rank: record.rank,
    baseSalary: record.baseSalary,
    allowances: {
      positionAllowance,
      overtimeAllowance,
      mealAllowance,
      transportAllowance,
      otherAllowance,
    },
    deductions: {
      nationalPension,
      healthInsurance,
      longTermCare,
      employmentInsurance,
      incomeTax,
      localIncomeTax,
      otherDeduction,
    },
    totalAllowance,
    totalDeduction,
    netPayment: record.baseSalary + totalAllowance - totalDeduction,
    paymentDate: record.paymentDate,
    status: record.status,
    year: record.year,
    month: record.month,
  };
};

export function SalaryManagement() {
  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('rank');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태
  const [startDate, setStartDate] = useState('2025-12-01');
  const [endDate, setEndDate] = useState('2025-12-31');

  // 다이얼로그 상태
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedSalaryDetail, setSelectedSalaryDetail] = useState<SalaryDetail | null>(null);

  // Mock 데이터
  const [salaryData, setSalaryData] = useState<SalaryRecord[]>(generateSalaryData);

  // ===== 체크박스 핸들러 =====
  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 === filteredData.length && filteredData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(filteredData.map(item => item.id)));
    }
  }, [selectedItems.size]);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    return salaryData.filter(item =>
      item.employeeName.includes(searchQuery) ||
      item.department.includes(searchQuery)
    );
  }, [salaryData, searchQuery]);

  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredData.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);

  // ===== 지급완료 핸들러 =====
  const handleMarkCompleted = useCallback(() => {
    if (selectedItems.size === 0) return;

    setSalaryData(prev => prev.map(item => {
      if (selectedItems.has(item.id)) {
        return { ...item, status: 'completed' as PaymentStatus };
      }
      return item;
    }));

    setSelectedItems(new Set());
    console.log('지급완료 처리:', Array.from(selectedItems));
  }, [selectedItems]);

  // ===== 지급예정 핸들러 =====
  const handleMarkScheduled = useCallback(() => {
    if (selectedItems.size === 0) return;

    setSalaryData(prev => prev.map(item => {
      if (selectedItems.has(item.id)) {
        return { ...item, status: 'scheduled' as PaymentStatus };
      }
      return item;
    }));

    setSelectedItems(new Set());
    console.log('지급예정 처리:', Array.from(selectedItems));
  }, [selectedItems]);

  // ===== 상세보기 핸들러 =====
  const handleViewDetail = useCallback((record: SalaryRecord) => {
    const detail = generateSalaryDetail(record);
    setSelectedSalaryDetail(detail);
    setDetailDialogOpen(true);
  }, []);

  // ===== 급여 상세 저장 핸들러 =====
  const handleSaveDetail = useCallback((updatedDetail: SalaryDetail) => {
    setSalaryData(prev => prev.map(item => {
      if (item.employeeId === updatedDetail.employeeId) {
        return {
          ...item,
          status: updatedDetail.status,
        };
      }
      return item;
    }));
    setDetailDialogOpen(false);
    console.log('급여 상세 저장:', updatedDetail);
  }, []);

  // ===== 지급항목 추가 핸들러 =====
  const handleAddPaymentItem = useCallback(() => {
    // TODO: 지급항목 추가 다이얼로그 또는 로직 구현
    console.log('지급항목 추가 클릭');
  }, []);

  // ===== 탭 (단일 탭) =====
  const [activeTab, setActiveTab] = useState('all');
  const tabs: TabOption[] = useMemo(() => [
    { value: 'all', label: '전체', count: salaryData.length, color: 'blue' },
  ], [salaryData.length]);

  // ===== 통계 카드 (총 실지급액, 총 기본급, 총 수당, 초과근무, 상여, 총공제) =====
  const statCards: StatCard[] = useMemo(() => {
    const totalNetPayment = salaryData.reduce((sum, s) => sum + s.netPayment, 0);
    const totalBaseSalary = salaryData.reduce((sum, s) => sum + s.baseSalary, 0);
    const totalAllowance = salaryData.reduce((sum, s) => sum + s.allowance, 0);
    const totalOvertime = salaryData.reduce((sum, s) => sum + s.overtime, 0);
    const totalBonus = salaryData.reduce((sum, s) => sum + s.bonus, 0);
    const totalDeduction = salaryData.reduce((sum, s) => sum + s.deduction, 0);

    return [
      {
        label: '총 실지급액',
        value: `${formatCurrency(totalNetPayment)}원`,
        icon: DollarSign,
        iconColor: 'text-green-500',
      },
      {
        label: '총 기본급',
        value: `${formatCurrency(totalBaseSalary)}원`,
        icon: Banknote,
        iconColor: 'text-blue-500',
      },
      {
        label: '총 수당',
        value: `${formatCurrency(totalAllowance)}원`,
        icon: Briefcase,
        iconColor: 'text-purple-500',
      },
      {
        label: '초과근무',
        value: `${formatCurrency(totalOvertime)}원`,
        icon: Timer,
        iconColor: 'text-orange-500',
      },
      {
        label: '상여',
        value: `${formatCurrency(totalBonus)}원`,
        icon: Gift,
        iconColor: 'text-pink-500',
      },
      {
        label: '총 공제',
        value: `${formatCurrency(totalDeduction)}원`,
        icon: MinusCircle,
        iconColor: 'text-red-500',
      },
    ];
  }, [salaryData]);

  // ===== 테이블 컬럼 (부서, 직책, 이름, 직급, 기본급, 수당, 초과근무, 상여, 공제, 실지급액, 일자, 상태, 작업) =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'department', label: '부서' },
    { key: 'position', label: '직책' },
    { key: 'name', label: '이름' },
    { key: 'rank', label: '직급' },
    { key: 'baseSalary', label: '기본급', className: 'text-right' },
    { key: 'allowance', label: '수당', className: 'text-right' },
    { key: 'overtime', label: '초과근무', className: 'text-right' },
    { key: 'bonus', label: '상여', className: 'text-right' },
    { key: 'deduction', label: '공제', className: 'text-right' },
    { key: 'netPayment', label: '실지급액', className: 'text-right' },
    { key: 'paymentDate', label: '일자', className: 'text-center' },
    { key: 'status', label: '상태', className: 'text-center' },
    { key: 'action', label: '작업', className: 'text-center w-[80px]' },
  ], []);

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

    return (
      <TableRow key={item.id} className="hover:bg-muted/50">
        <TableCell className="text-center">
          <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
        </TableCell>
        <TableCell>{item.department}</TableCell>
        <TableCell>{item.position}</TableCell>
        <TableCell className="font-medium">{item.employeeName}</TableCell>
        <TableCell>{item.rank}</TableCell>
        <TableCell className="text-right">{formatCurrency(item.baseSalary)}원</TableCell>
        <TableCell className="text-right">{formatCurrency(item.allowance)}원</TableCell>
        <TableCell className="text-right">{formatCurrency(item.overtime)}원</TableCell>
        <TableCell className="text-right">{formatCurrency(item.bonus)}원</TableCell>
        <TableCell className="text-right text-red-600">-{formatCurrency(item.deduction)}원</TableCell>
        <TableCell className="text-right font-medium text-green-600">{formatCurrency(item.netPayment)}원</TableCell>
        <TableCell className="text-center">{item.paymentDate}</TableCell>
        <TableCell className="text-center">
          <Badge className={PAYMENT_STATUS_COLORS[item.status]}>
            {PAYMENT_STATUS_LABELS[item.status]}
          </Badge>
        </TableCell>
        <TableCell className="text-center">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleViewDetail(item)}
            title="수정"
          >
            <Pencil className="h-4 w-4" />
          </Button>
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleViewDetail]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: SalaryRecord,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.employeeName}
        headerBadges={
          <Badge className={PAYMENT_STATUS_COLORS[item.status]}>
            {PAYMENT_STATUS_LABELS[item.status]}
          </Badge>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="부서" value={item.department} />
            <InfoField label="직급" value={item.rank} />
            <InfoField label="기본급" value={`${formatCurrency(item.baseSalary)}원`} />
            <InfoField label="수당" value={`${formatCurrency(item.allowance)}원`} />
            <InfoField label="초과근무" value={`${formatCurrency(item.overtime)}원`} />
            <InfoField label="상여" value={`${formatCurrency(item.bonus)}원`} />
            <InfoField label="공제" value={`-${formatCurrency(item.deduction)}원`} />
            <InfoField label="실지급액" value={`${formatCurrency(item.netPayment)}원`} />
            <InfoField label="지급일" value={item.paymentDate} />
          </div>
        }
        actions={
          <Button
            variant="outline"
            size="sm"
            className="w-full"
            onClick={() => handleViewDetail(item)}
          >
            <Pencil className="h-4 w-4 mr-2" />
            수정
          </Button>
        }
      />
    );
  }, [handleViewDetail]);

  // ===== 헤더 액션 =====
  const headerActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 날짜 범위 선택 */}
      <div className="flex items-center gap-1">
        <Input
          type="date"
          value={startDate}
          onChange={(e) => setStartDate(e.target.value)}
          className="w-[140px]"
        />
        <span className="text-muted-foreground">~</span>
        <Input
          type="date"
          value={endDate}
          onChange={(e) => setEndDate(e.target.value)}
          className="w-[140px]"
        />
      </div>

      {/* 지급완료/지급예정 버튼 - 선택된 항목이 있을 때만 표시 */}
      {selectedItems.size > 0 && (
        <>
          <Button variant="default" onClick={handleMarkCompleted}>
            <Check className="h-4 w-4 mr-2" />
            지급완료
          </Button>
          <Button variant="outline" onClick={handleMarkScheduled}>
            <Clock className="h-4 w-4 mr-2" />
            지급예정
          </Button>
        </>
      )}

      <Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
        <Download className="h-4 w-4 mr-2" />
        엑셀 다운로드
      </Button>
    </div>
  );

  // ===== 정렬 필터 =====
  const extraFilters = (
    <Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
      <SelectTrigger className="w-[120px]">
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {Object.entries(SORT_OPTIONS).map(([key, label]) => (
          <SelectItem key={key} value={key}>{label}</SelectItem>
        ))}
      </SelectContent>
    </Select>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="급여관리"
        description="직원들의 급여 현황을 관리합니다"
        icon={DollarSign}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="이름, 부서 검색..."
        extraFilters={extraFilters}
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: SalaryRecord) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 급여 상세 다이얼로그 */}
      <SalaryDetailDialog
        open={detailDialogOpen}
        onOpenChange={setDetailDialogOpen}
        salaryDetail={selectedSalaryDetail}
        onSave={handleSaveDetail}
        onAddPaymentItem={handleAddPaymentItem}
      />
    </>
  );
}