'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { toast } from 'sonner';
import { Car, DollarSign, CreditCard, Gauge } from 'lucide-react';
import { TableRow, TableCell } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
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 { Trash2, Download } from 'lucide-react';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { VehicleFormDialog } from './VehicleFormDialog';
import { getCorporateVehicles, deleteCorporateVehicle } from './actions';
import { downloadExcel, type ExcelColumn } from '@/lib/utils/excel-download';
import {
  type CorporateVehicle,
  type OwnershipType,
  type VehicleStatus,
  OWNERSHIP_LABELS,
  OWNERSHIP_COLORS,
  STATUS_LABELS,
  STATUS_COLORS,
  formatCurrency,
  formatDistance,
} from '../types';

const PAGE_SIZE = 20;

const TABLE_COLUMNS: TableColumn[] = [
  { key: 'no', label: '번호', className: 'text-center w-[60px]' },
  { key: 'vehicle', label: '차량', className: 'min-w-[200px]' },
  { key: 'plateNumber', label: '차량번호', className: 'w-[120px]', copyable: true },
  { key: 'ownershipType', label: '구분', className: 'text-center w-[100px]' },
  { key: 'driver', label: '운전자', className: 'w-[80px]' },
  { key: 'price', label: '취득가/월렌트료', className: 'text-right w-[140px]' },
  { key: 'status', label: '상태', className: 'text-center w-[80px]' },
];

export function CorporateVehicleList() {
  const [data, setData] = useState<CorporateVehicle[]>([]);
  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 [filterOwnership, setFilterOwnership] = useState('all');
  const [filterStatus, setFilterStatus] = useState('all');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

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

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

  // 데이터 조회
  const fetchData = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getCorporateVehicles({
        page: currentPage,
        perPage: PAGE_SIZE,
        search: search || undefined,
        ownershipType: filterOwnership,
        status: filterStatus,
      });
      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, filterOwnership, filterStatus]);

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

  // 선택
  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(() => {
    setSelectedVehicle(null);
    setDialogMode('create');
    setDialogOpen(true);
  }, []);

  const handleEdit = useCallback((vehicle: CorporateVehicle) => {
    setSelectedVehicle(vehicle);
    setDialogMode('edit');
    setDialogOpen(true);
  }, []);

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

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

  // 엑셀 다운로드
  const excelColumns: ExcelColumn<CorporateVehicle>[] = useMemo(() => [
    { header: '차량번호', key: 'plateNumber', width: 15 },
    { header: '모델', key: 'model', width: 20 },
    { header: '종류', key: 'vehicleType', width: 10 },
    { header: '연식', key: 'year', width: 8 },
    { header: '구분', key: 'ownershipType', width: 10, transform: (val) => OWNERSHIP_LABELS[val as OwnershipType] || String(val) },
    { header: '운전자', key: 'driver', width: 10 },
    { header: '취득가', key: 'purchasePrice', width: 15, transform: (val) => Number(val) || 0 },
    { header: '월렌트료', key: 'monthlyRent', width: 15, transform: (val) => Number(val) || 0 },
    { header: '주행거리(km)', key: 'mileage', width: 15, transform: (val) => Number(val) || 0 },
    { header: '상태', key: 'status', width: 10, transform: (val) => STATUS_LABELS[val as VehicleStatus] || String(val) },
  ], []);

  const handleExcelDownload = useCallback(async () => {
    try {
      toast.info('엑셀 파일 생성 중...');
      const allData: CorporateVehicle[] = [];
      let page = 1;
      let lastPage = 1;
      do {
        const result = await getCorporateVehicles({
          page,
          perPage: 100,
          search: search || undefined,
          ownershipType: filterOwnership,
          status: filterStatus,
        });
        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, filterOwnership, filterStatus, excelColumns]);

  // 통계
  const stats = useMemo(() => {
    const corporatePrice = data
      .filter((v) => v.ownershipType === 'corporate')
      .reduce((sum, v) => sum + (v.purchasePrice || 0), 0);
    const monthlyRent = data
      .filter((v) => v.ownershipType === 'rent' || v.ownershipType === 'lease')
      .reduce((sum, v) => sum + (v.monthlyRent || 0), 0);
    const monthlyCount = data.filter(
      (v) => v.ownershipType === 'rent' || v.ownershipType === 'lease'
    ).length;
    const totalMileage = data.reduce((sum, v) => sum + (v.mileage || 0), 0);
    const activeCount = data.filter((v) => v.status === 'active').length;

    return [
      {
        label: '총 차량',
        value: `${totalItems}대`,
        description: `운행중 ${activeCount}대`,
        icon: Car,
        iconColor: 'text-gray-600' as const,
      },
      {
        label: '법인차량 취득가',
        value: formatCurrency(corporatePrice),
        description: `${data.filter((v) => v.ownershipType === 'corporate').length}대`,
        icon: DollarSign,
        iconColor: 'text-blue-600' as const,
      },
      {
        label: '월 렌트/리스료',
        value: formatCurrency(monthlyRent),
        description: `${monthlyCount}대`,
        icon: CreditCard,
        iconColor: 'text-blue-600' as const,
      },
      {
        label: '총 주행거리',
        value: formatDistance(totalMileage),
        icon: Gauge,
        iconColor: 'text-gray-600' as const,
      },
    ];
  }, [data, totalItems]);

  // 통합 필터 (PC: 인라인, 모바일: 바텀시트 자동 분기)
  const filterConfig: FilterFieldConfig[] = useMemo(() => [
    {
      key: 'ownership',
      label: '구분',
      type: 'single' as const,
      options: [
        { value: 'corporate', label: '법인차량' },
        { value: 'rent', label: '렌트차량' },
        { value: 'lease', label: '리스차량' },
      ],
      allOptionLabel: '전체 구분',
    },
    {
      key: 'status',
      label: '상태',
      type: 'single' as const,
      options: [
        { value: 'active', label: '운행중' },
        { value: 'maintenance', label: '정비중' },
        { value: 'disposed', label: '처분' },
      ],
      allOptionLabel: '전체 상태',
    },
  ], []);

  const filterValues: FilterValues = useMemo(() => ({
    ownership: filterOwnership,
    status: filterStatus,
  }), [filterOwnership, filterStatus]);

  const handleFilterChange = useCallback((key: string, value: string | string[]) => {
    if (key === 'ownership') { setFilterOwnership(value as string); setCurrentPage(1); }
    if (key === 'status') { setFilterStatus(value as string); setCurrentPage(1); }
  }, []);

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


  // 테이블 행 렌더
  const renderTableRow = useCallback(
    (item: CorporateVehicle, _index: number, globalIndex: number) => {
      const isCorporate = item.ownershipType === 'corporate';
      const priceText = isCorporate
        ? formatCurrency(item.purchasePrice || 0)
        : `${formatCurrency(item.monthlyRent || 0)}/월`;

      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>
            <div>
              <div className="font-medium truncate max-w-[200px]">{item.model}</div>
              <div className="text-xs text-muted-foreground">
                {item.vehicleType}{item.year ? ` · ${item.year}년` : ''}
              </div>
            </div>
          </TableCell>
          <TableCell className="font-mono">{item.plateNumber}</TableCell>
          <TableCell className="text-center">
            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${OWNERSHIP_COLORS[item.ownershipType]}`}>
              {OWNERSHIP_LABELS[item.ownershipType]}
            </span>
          </TableCell>
          <TableCell>{item.driver || '-'}</TableCell>
          <TableCell className="text-right">{priceText}</TableCell>
          <TableCell className="text-center">
            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[item.status]}`}>
              {STATUS_LABELS[item.status]}
            </span>
          </TableCell>
        </TableRow>
      );
    },
    [handleEdit, handleDeleteClick]
  );

  // 모바일 카드 렌더
  const renderMobileCard = useCallback(
    (
      item: CorporateVehicle,
      _index: number,
      _globalIndex: number,
      isSelected: boolean,
      onToggle: () => void
    ) => {
      const isCorporate = item.ownershipType === 'corporate';
      const priceText = isCorporate
        ? formatCurrency(item.purchasePrice || 0)
        : `${formatCurrency(item.monthlyRent || 0)}/월`;

      return (
        <MobileCard
          key={item.id}
          title={item.model}
          subtitle={`${item.plateNumber} · ${item.vehicleType}${item.year ? ` · ${item.year}년` : ''}`}
          headerBadges={
            <div className="flex gap-1">
              <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${OWNERSHIP_COLORS[item.ownershipType]}`}>
                {OWNERSHIP_LABELS[item.ownershipType]}
              </span>
              <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[item.status]}`}>
                {STATUS_LABELS[item.status]}
              </span>
            </div>
          }
          infoGrid={[
            <InfoField key="driver" label="운전자" value={item.driver || '-'} />,
            <InfoField key="price" label={isCorporate ? '취득가' : '월렌트료'} value={priceText} />,
            <InfoField key="mileage" label="주행거리" value={formatDistance(item.mileage)} />,
          ]}
          isSelected={isSelected}
          onToggleSelection={onToggle}
          onClick={() => handleEdit(item)}
        />
      );
    },
    [handleEdit]
  );

  return (
    <>
      <IntegratedListTemplateV2<CorporateVehicle>
        title="법인차량관리"
        description="Corporate Vehicles"
        icon={Car}
        // 검색
        searchValue={search}
        onSearchChange={(v) => { setSearch(v); setCurrentPage(1); }}
        searchPlaceholder="차량번호, 모델, 운전자 검색..."
        // 헤더 액션 (엑셀 다운로드)
        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}
      />

      <VehicleFormDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        mode={dialogMode}
        vehicle={selectedVehicle}
        onSuccess={fetchData}
      />

      <DeleteConfirmDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        description={`${deleteTarget?.model || ''} (${deleteTarget?.plateNumber || ''})을(를) 삭제하시겠습니까?`}
        loading={isDeleting}
        onConfirm={handleDeleteConfirm}
      />
    </>
  );
}
