import { FileImage, FileSpreadsheet, FileText } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import type { ProcurementMaterial, SourceFileRecord } from '@/types';
import type { ParsedMaterialRow } from '@/lib/materialImportParser';
import type { ProcurementMaterialInsert } from '@/services/materialService';

export function renderUploadError(error: unknown): string {
  if (error instanceof Error) return error.message;
  if (
    error
    && typeof error === 'object'
    && 'message' in error
    && typeof (error as { message: unknown }).message === 'string'
  ) {
    return (error as { message: string }).message;
  }
  return '操作失败，请检查 Supabase 配置、bucket 和策略。';
}

export function deriveMaterialName(fileName: string): string {
  const trimmedName = fileName.trim();
  const dotIndex = trimmedName.lastIndexOf('.');
  const baseName = dotIndex > 0 ? trimmedName.slice(0, dotIndex) : trimmedName;
  return baseName || '未填';
}

export function isSpreadsheetFile(fileName: string): boolean {
  const ext = fileName.split('.').pop()?.toLowerCase() ?? '';
  return ext === 'xlsx' || ext === 'xls';
}

export function looksLikeUuid(value: string): boolean {
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
}

/** 上传后端尚未持久化、仅在前端 draft 列表里的物料 */
export function isLocalDraftMaterial(row: ProcurementMaterial): boolean {
  return row.id.startsWith('mat-') || !looksLikeUuid(row.id);
}

export function matchesMaterialDeletionTarget(
  item: ProcurementMaterial,
  row: ProcurementMaterial,
): boolean {
  return item.id === row.id;
}

export function buildUploadedMaterialInput(
  record: SourceFileRecord,
  createdByUserId?: string,
  parsedRow?: ParsedMaterialRow,
): ProcurementMaterialInsert {
  const material: ProcurementMaterialInsert = {
    material_name: parsedRow?.material_name || deriveMaterialName(record.file_name),
    specification: parsedRow?.specification || '',
    quantity: parsedRow?.quantity ?? 0,
    unit: parsedRow?.unit || '',
    technical_standard: parsedRow?.technical_standard || '',
    material_requirement: parsedRow?.material_requirement || '',
    technical_requirement: parsedRow?.technical_requirement || '',
    applicable_conditions: parsedRow?.applicable_conditions || '',
    test_requirement: parsedRow?.test_requirement || '',
    acceptance_note: parsedRow?.acceptance_note || '',
    warranty_period: parsedRow?.warranty_period || '',
    deadline: parsedRow?.deadline || '',
    invoice_type: parsedRow?.invoice_type || '',
    brand: parsedRow?.brand || '',
    remarks: parsedRow?.remarks || '',
    delivery_address: parsedRow?.delivery_address || '',
    source_file: record.file_name,
    source_file_id: record.id,
    batch_id: record.batch_id,
  };

  if (createdByUserId) {
    material.created_by = createdByUserId;
  }

  return material;
}

interface FileIconDescriptor {
  Icon: LucideIcon;
  iconClass: string;
  badge: string;
  badgeClass: string;
}

export function getFileIcon(name: string): FileIconDescriptor {
  const ext = name.split('.').pop()?.toLowerCase() ?? '';
  if (['xlsx', 'xls'].includes(ext)) {
    return {
      Icon: FileSpreadsheet,
      iconClass: 'text-green-600',
      badge: 'Excel',
      badgeClass: 'bg-green-50 text-green-700 border-green-200',
    };
  }
  if (ext === 'pdf') {
    return {
      Icon: FileText,
      iconClass: 'text-red-500',
      badge: 'PDF',
      badgeClass: 'bg-red-50 text-red-600 border-red-200',
    };
  }
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) {
    return {
      Icon: FileImage,
      iconClass: 'text-blue-500',
      badge: '图片',
      badgeClass: 'bg-blue-50 text-blue-600 border-blue-200',
    };
  }
  return {
    Icon: FileText,
    iconClass: 'text-muted-foreground',
    badge: ext.toUpperCase() || '文件',
    badgeClass: 'bg-muted text-muted-foreground border-border',
  };
}
