'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import { BookOpen, Route, Briefcase, User, MapPin, Copy, Edit, Trash2, Download } from 'lucide-react';
import { TableRow, TableCell } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type FilterFieldConfig,
  type FilterValues,
} from '@/components/templates/IntegratedListTemplateV2';
import { useColumnSettings } from '@/hooks/useColumnSettings';
import { ColumnSettingsPopover } from '@/components/molecules/ColumnSettingsPopover';
import { MobileCard, InfoField } from '@/components/organisms/MobileCard';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { VehicleLogFormDialog } from './VehicleLogFormDialog';
import { getVehicleLogs, getVehicleLogSummary, deleteVehicleLog } from './actions';
import { getVehicleDropdown } from '../CorporateVehicles/actions';
import { downloadExcel, type ExcelColumn } from '@/lib/utils/excel-download';
import {
  type VehicleLog,
  type VehicleDropdownItem,
  type VehicleLogSummary,
  type TripType,
  TRIP_TYPE_LABELS,
  TRIP_TYPE_COLORS,
  LOCATION_TYPE_LABELS,
  type LocationType,
  formatDistance,
} from '../types';

const PAGE_SIZE = 20;

const TABLE_COLUMNS: TableColumn[] = [
  { key: 'no', label: '번호', className: 'text-center w-[60px]' },
  { key: 'logDate', label: '날짜', className: 'w-[100px]' },
  { key: 'vehicle', label: '차량', className: 'w-[140px]' },
  { key: 'driver', label: '부서/성명', className: 'w-[120px]' },
  { key: 'tripType', label: '구분', className: 'text-center w-[90px]' },
  { key: 'departure', label: '출발지', className: 'min-w-[140px]' },
  { key: 'arrival', label: '도착지', className: 'min-w-[140px]' },
  { key: 'distanceKm', label: '주행(km)', className: 'text-right w-[90px]' },
  { key: 'note', label: '비고', className: 'min-w-[120px]' },
  { key: 'actions', label: '관리', className: 'text-center w-[100px]' },
];

const now = new Date();
const CURRENT_YEAR = now.getFullYear();
const CURRENT_MONTH = now.getMonth() + 1;
const YEAR_OPTIONS = Array.from({ length: 5 }, (_, i) => CURRENT_YEAR - 2 + i);
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, i) => i + 1);

export function VehicleLogList() {
  const [data, setData] = useState<VehicleLog[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [search, setSearch] = useState('');
  const [year, setYear] = useState(CURRENT_YEAR);
  const [month, setMonth] = useState(CURRENT_MONTH);
  const [filterVehicle, setFilterVehicle] = useState('all');
  const [filterTripType, setFilterTripType] = useState('all');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // 드롭다운 차량 목록
  const [vehicles, setVehicles] = useState<VehicleDropdownItem[]>([]);
  // 월별 통계
  const [summary, setSummary] = useState<VehicleLogSummary | null>(null);

  // 모달 상태
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<'create' | 'edit'>('create');
  const [selectedLog, setSelectedLog] = useState<VehicleLog | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<VehicleLog | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // 컬럼 설정
  const {
    visibleColumns,
    allColumnsWithVisibility,
    columnWidths,
    setColumnWidth,
    toggleColumnVisibility,
    resetSettings,
    hasHiddenColumns,
  } = useColumnSettings({
    pageId: 'vehicle-logs',
    columns: TABLE_COLUMNS,
    alwaysVisibleKeys: ['no', 'logDate', 'vehicle', 'tripType', 'actions'],
  });

  // 차량 드롭다운 로드
  useEffect(() => {
    getVehicleDropdown().then((result) => {
      if (result.success && result.data) {
        setVehicles(Array.isArray(result.data) ? result.data : []);
      }
    });
  }, []);

  // 데이터 조회
  const fetchData = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getVehicleLogs({
        page: currentPage,
        perPage: PAGE_SIZE,
        search: search || undefined,
        vehicleId: filterVehicle,
        year,
        month,
        tripType: filterTripType,
      });
      if (result.success) {
        setData(result.data);
        setTotalPages(result.pagination.lastPage);
        setTotalItems(result.pagination.total);
      } else {
        toast.error(result.error || '조회에 실패했습니다.');
        setData([]);
      }
    } catch {
      toast.error('조회 중 오류가 발생했습니다.');
      setData([]);
    } finally {
      setIsLoading(false);
    }
  }, [currentPage, search, filterVehicle, year, month, filterTripType]);

  // 통계 조회
  const fetchSummary = useCallback(async () => {
    try {
      const result = await getVehicleLogSummary({
        vehicleId: filterVehicle,
        year,
        month,
      });
      if (result.success && result.data) {
        setSummary(result.data);
      }
    } catch {
      // 통계 실패 시 무시
    }
  }, [filterVehicle, year, month]);

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

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

  // 선택
  const toggleSelection = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }, []);

  const toggleSelectAll = useCallback(() => {
    setSelectedIds((prev) =>
      prev.size === data.length
        ? new Set()
        : new Set(data.map((item) => String(item.id)))
    );
  }, [data]);

  // 모달 핸들러
  const handleCreate = useCallback(() => {
    setSelectedLog(null);
    setDialogMode('create');
    setDialogOpen(true);
  }, []);

  const handleEdit = useCallback((log: VehicleLog) => {
    setSelectedLog(log);
    setDialogMode('edit');
    setDialogOpen(true);
  }, []);

  // 복사 (기존 기록 기반, 날짜만 오늘)
  const handleCopy = useCallback((log: VehicleLog) => {
    setSelectedLog({ ...log, id: 0, logDate: new Date().toISOString().slice(0, 10) });
    setDialogMode('create');
    setDialogOpen(true);
  }, []);

  const handleDeleteClick = useCallback((log: VehicleLog) => {
    setDeleteTarget(log);
    setDeleteOpen(true);
  }, []);

  const handleDeleteConfirm = useCallback(async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    try {
      const result = await deleteVehicleLog(deleteTarget.id);
      if (result.success) {
        toast.success('운행기록이 삭제되었습니다.');
        setDeleteOpen(false);
        setDeleteTarget(null);
        fetchData();
        fetchSummary();
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsDeleting(false);
    }
  }, [deleteTarget, fetchData, fetchSummary]);

  const handleSuccess = useCallback(() => {
    fetchData();
    fetchSummary();
  }, [fetchData, fetchSummary]);

  // 엑셀 다운로드
  const excelColumns: ExcelColumn<VehicleLog>[] = useMemo(() => [
    { header: '날짜', key: 'logDate', width: 12 },
    { header: '차량번호', key: 'vehicle', width: 15, transform: (_, row) => row.vehicle?.plateNumber || '-' },
    { header: '차량모델', key: 'vehicle', width: 15, transform: (_, row) => row.vehicle?.model || '-' },
    { header: '운전자', key: 'driverName', width: 10 },
    { header: '부서', key: 'department', width: 10 },
    { header: '구분', key: 'tripType', width: 12, transform: (val) => TRIP_TYPE_LABELS[val as TripType] || String(val) },
    { header: '출발지', key: 'departureName', width: 15 },
    { header: '도착지', key: 'arrivalName', width: 15 },
    { header: '주행거리(km)', key: 'distanceKm', width: 15, transform: (val) => Number(val) || 0 },
    { header: '비고', key: 'note', width: 20 },
  ], []);

  const handleExcelDownload = useCallback(async () => {
    try {
      toast.info('엑셀 파일 생성 중...');
      const allData: VehicleLog[] = [];
      let page = 1;
      let lastPage = 1;
      do {
        const result = await getVehicleLogs({
          page,
          perPage: 100,
          search: search || undefined,
          vehicleId: filterVehicle,
          year,
          month,
          tripType: filterTripType,
        });
        if (result.success && result.data.length > 0) {
          allData.push(...result.data);
          lastPage = result.pagination.lastPage;
        }
        page++;
      } while (page <= lastPage);

      if (allData.length > 0) {
        await downloadExcel({ data: allData as unknown as Record<string, unknown>[], columns: excelColumns as unknown as ExcelColumn[], filename: '차량일지', sheetName: '차량일지' });
        toast.success(`${allData.length}건 다운로드 완료`);
      } else {
        toast.warning('다운로드할 데이터가 없습니다.');
      }
    } catch {
      toast.error('엑셀 다운로드에 실패했습니다.');
    }
  }, [search, filterVehicle, year, month, filterTripType, excelColumns]);

  // 통계
  const stats = useMemo(() => {
    const s = summary;
    return [
      {
        label: '전체',
        value: formatDistance(s?.totalDistance ?? 0),
        description: `${s?.totalCount ?? 0}건`,
        icon: Route,
        iconColor: 'text-gray-600' as const,
      },
      {
        label: '출근용',
        value: formatDistance(s?.commuteToDistance ?? 0),
        description: `${s?.commuteToCount ?? 0}건`,
        icon: MapPin,
        iconColor: 'text-green-600' as const,
      },
      {
        label: '퇴근용',
        value: formatDistance(s?.commuteFromDistance ?? 0),
        description: `${s?.commuteFromCount ?? 0}건`,
        icon: MapPin,
        iconColor: 'text-green-600' as const,
      },
      {
        label: '업무용',
        value: formatDistance(s?.businessDistance ?? 0),
        description: `${s?.businessCount ?? 0}건`,
        icon: Briefcase,
        iconColor: 'text-blue-600' as const,
      },
      {
        label: '비업무',
        value: formatDistance(s?.personalDistance ?? 0),
        description: `${s?.personalCount ?? 0}건`,
        icon: User,
        iconColor: 'text-gray-600' as const,
      },
    ];
  }, [summary]);

  // 통합 필터 (PC: 인라인, 모바일: 바텀시트 자동 분기)
  const filterConfig: FilterFieldConfig[] = useMemo(() => [
    {
      key: 'vehicle',
      label: '차량',
      type: 'single' as const,
      options: vehicles.map((v) => ({ value: String(v.id), label: `${v.plateNumber} (${v.model})` })),
      allOptionLabel: '전체 차량',
    },
    {
      key: 'tripType',
      label: '구분',
      type: 'single' as const,
      options: (Object.entries(TRIP_TYPE_LABELS) as [TripType, string][]).map(([key, label]) => ({
        value: key,
        label,
      })),
      allOptionLabel: '전체 구분',
    },
  ], [vehicles]);

  const filterValues: FilterValues = useMemo(() => ({
    vehicle: filterVehicle,
    tripType: filterTripType,
  }), [filterVehicle, filterTripType]);

  const handleFilterChange = useCallback((key: string, value: string | string[]) => {
    if (key === 'vehicle') { setFilterVehicle(value as string); setCurrentPage(1); }
    if (key === 'tripType') { setFilterTripType(value as string); setCurrentPage(1); }
  }, []);

  const handleFilterReset = useCallback(() => {
    setFilterVehicle('all');
    setFilterTripType('all');
    setCurrentPage(1);
  }, []);

  // 위치 정보 표시 함수
  const formatLocation = (type: LocationType | string, name: string | null) => {
    const typeLabel = LOCATION_TYPE_LABELS[type as LocationType] || '';
    return name ? `${typeLabel ? `[${typeLabel}] ` : ''}${name}` : typeLabel || '-';
  };

  // 테이블 행 렌더
  const renderTableRow = useCallback(
    (item: VehicleLog, _index: number, globalIndex: number) => {
      const vehicleText = item.vehicle
        ? `${item.vehicle.plateNumber}`
        : '-';

      return (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleEdit(item)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox
              checked={selectedIds.has(String(item.id))}
              onCheckedChange={() => toggleSelection(String(item.id))}
            />
          </TableCell>
          <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
          <TableCell className="font-mono text-sm">{item.logDate}</TableCell>
          <TableCell>
            <div className="truncate max-w-[130px]">{vehicleText}</div>
            {item.vehicle && (
              <div className="text-xs text-muted-foreground truncate">{item.vehicle.model}</div>
            )}
          </TableCell>
          <TableCell>
            <div>{item.driverName}</div>
            {item.department && (
              <div className="text-xs text-muted-foreground">{item.department}</div>
            )}
          </TableCell>
          <TableCell className="text-center">
            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${TRIP_TYPE_COLORS[item.tripType]}`}>
              {TRIP_TYPE_LABELS[item.tripType]}
            </span>
          </TableCell>
          <TableCell className="text-sm">
            {formatLocation(item.departureType, item.departureName)}
          </TableCell>
          <TableCell className="text-sm">
            {formatLocation(item.arrivalType, item.arrivalName)}
          </TableCell>
          <TableCell className="text-right font-mono">
            {item.distanceKm ? item.distanceKm.toLocaleString() : '-'}
          </TableCell>
          <TableCell className="text-sm text-muted-foreground truncate max-w-[120px]">
            {item.note || '-'}
          </TableCell>
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-center gap-1">
              <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleEdit(item)}>
                <Edit className="h-3.5 w-3.5" />
              </Button>
              <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => handleCopy(item)}>
                <Copy className="h-3.5 w-3.5" />
              </Button>
              <Button variant="ghost" size="icon" className="h-7 w-7 text-red-500" onClick={() => handleDeleteClick(item)}>
                <Trash2 className="h-3.5 w-3.5" />
              </Button>
            </div>
          </TableCell>
        </TableRow>
      );
    },
    [handleEdit, handleCopy, handleDeleteClick]
  );

  // 모바일 카드 렌더
  const renderMobileCard = useCallback(
    (
      item: VehicleLog,
      _index: number,
      _globalIndex: number,
      isSelected: boolean,
      onToggle: () => void
    ) => {
      const vehicleText = item.vehicle
        ? `${item.vehicle.plateNumber} (${item.vehicle.model})`
        : '-';

      return (
        <MobileCard
          key={item.id}
          title={`${item.logDate} · ${item.driverName}`}
          subtitle={vehicleText}
          headerBadges={
            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${TRIP_TYPE_COLORS[item.tripType]}`}>
              {TRIP_TYPE_LABELS[item.tripType]}
            </span>
          }
          infoGrid={[
            <InfoField key="departure" label="출발지" value={formatLocation(item.departureType, item.departureName)} />,
            <InfoField key="arrival" label="도착지" value={formatLocation(item.arrivalType, item.arrivalName)} />,
            <InfoField key="distance" label="주행거리" value={item.distanceKm ? formatDistance(item.distanceKm) : '-'} />,
          ]}
          isSelected={isSelected}
          onToggleSelection={onToggle}
          onClick={() => handleEdit(item)}
        />
      );
    },
    [handleEdit]
  );

  return (
    <>
      <IntegratedListTemplateV2<VehicleLog>
        title="차량일지"
        description="Vehicle Driving Logs"
        icon={BookOpen}
        // 검색
        searchValue={search}
        onSearchChange={(v) => { setSearch(v); setCurrentPage(1); }}
        searchPlaceholder="운전자, 출발지, 도착지 검색..."
        // 날짜 선택 (year/month)
        dateRangeSelector={{
          enabled: true,
          hideDateInputs: true,
          showPresets: false,
          extraActions: (
            <div className="flex items-center gap-2 flex-wrap">
              <Select value={String(year)} onValueChange={(v) => { setYear(Number(v)); setCurrentPage(1); }}>
                <SelectTrigger className="w-[100px] h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {YEAR_OPTIONS.map((y) => (
                    <SelectItem key={y} value={String(y)}>{y}년</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={String(month)} onValueChange={(v) => { setMonth(Number(v)); setCurrentPage(1); }}>
                <SelectTrigger className="w-[80px] h-9">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MONTH_OPTIONS.map((m) => (
                    <SelectItem key={m} value={String(m)}>{m}월</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          ),
        }}
        // 헤더 액션 (엑셀 다운로드)
        headerActions={(
          <Button variant="outline" size="sm" onClick={handleExcelDownload}>
            <Download className="mr-1 h-4 w-4" />
            엑셀 다운로드
          </Button>
        )}
        // 등록 버튼
        createButton={{ label: '운행기록 등록', onClick: handleCreate }}
        // 통계
        stats={stats}
        // 통합 필터 (PC: 인라인, 모바일: 바텀시트)
        filterConfig={filterConfig}
        filterValues={filterValues}
        onFilterChange={handleFilterChange}
        onFilterReset={handleFilterReset}
        filterTitle="운행 필터"
        // 컬럼
        tableColumns={visibleColumns}
        columnSettings={{
          columnWidths,
          onColumnResize: setColumnWidth,
          settingsPopover: (
            <ColumnSettingsPopover
              columns={allColumnsWithVisibility}
              onToggle={toggleColumnVisibility}
              onReset={resetSettings}
              hasHiddenColumns={hasHiddenColumns}
            />
          ),
        }}
        // 데이터
        data={data}
        selectedItems={selectedIds}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item) => String(item.id)}
        // 렌더링
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        // 페이지네이션
        pagination={{
          currentPage,
          totalPages,
          totalItems,
          itemsPerPage: PAGE_SIZE,
          onPageChange: setCurrentPage,
        }}
        isLoading={isLoading}
      />

      <VehicleLogFormDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        mode={dialogMode}
        log={selectedLog}
        vehicles={vehicles}
        onSuccess={handleSuccess}
      />

      <DeleteConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        description="이 운행기록을 삭제하시겠습니까?"
        loading={isDeleting}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}
