'use client';

/**
 * 견적관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (탭별, 검색)
 * - 통계 카드 (클라이언트 데이터 기반 계산)
 * - 산출내역서 다이얼로그
 * - 삭제/일괄삭제 다이얼로그
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import {
  FileText,
  Edit,
  Trash2,
  CheckCircle,
  History,
  Calculator,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { getQuoteStatusBadge } from '@/components/atoms/BadgeSm';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Table,
  TableHeader,
  TableHead,
  TableBody,
} from '@/components/ui/table';
import { Separator } from '@/components/ui/separator';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { StandardDialog } from '@/components/molecules/StandardDialog';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { useDeleteDialog } from '@/hooks/useDeleteDialog';
import { toast } from 'sonner';
import { formatAmount, formatAmountManwon } from '@/lib/utils/amount';
import type { Quote } from './types';
import { PRODUCT_CATEGORY_LABELS } from './types';
import { getQuotes, deleteQuote, bulkDeleteQuotes } from './actions';
import type { PaginationMeta } from '@/lib/api/types';

// ===== Props 타입 =====
interface QuoteManagementClientProps {
  initialData: Quote[];
  initialPagination: PaginationMeta;
}

export function QuoteManagementClient({
  initialData,
  initialPagination: _initialPagination,
}: QuoteManagementClientProps) {
  const router = useRouter();
  const deleteDialog = useDeleteDialog({
    onDelete: deleteQuote,
    onBulkDelete: bulkDeleteQuotes,
    onSuccess: () => window.location.reload(),
    entityName: '견적',
  });

  // ===== 날짜 필터 상태 =====
  const today = new Date();
  const [startDate, setStartDate] = useState(format(startOfMonth(today), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(format(endOfMonth(today), 'yyyy-MM-dd'));

  // ===== 필터 상태 =====
  const [productCategoryFilter, setProductCategoryFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');

  // ===== 산출내역서 다이얼로그 상태 =====
  const [isCalculationDialogOpen, setIsCalculationDialogOpen] = useState(false);
  const [calculationQuote, setCalculationQuote] = useState<Quote | null>(null);

  // ===== 전체 데이터 상태 (통계 계산용) =====
  const [allQuotes, setAllQuotes] = useState<Quote[]>(initialData);

  // ===== 핸들러 =====
  const handleView = useCallback((quote: Quote) => {
    router.push(`/sales/quote-management/${quote.id}?mode=view`);
  }, [router]);

  const handleEdit = useCallback((quote: Quote) => {
    router.push(`/sales/quote-management/${quote.id}?mode=edit`);
  }, [router]);

  const handleViewHistory = useCallback((quote: Quote) => {
    toast.info(`수정 이력: ${quote.quoteNumber} (${quote.currentRevision}차 수정)`);
  }, []);

  const _handleViewCalculation = useCallback((quote: Quote) => {
    setCalculationQuote(quote);
    setIsCalculationDialogOpen(true);
  }, []);

  // ===== 상태 뱃지 =====
  const getRevisionBadge = useCallback((quote: Quote) => {
    const legacyQuote = {
      status: quote.status === 'converted' ? 'converted' : 'draft',
      currentRevision: quote.currentRevision,
      isFinal: quote.isFinal,
    };
    return getQuoteStatusBadge(legacyQuote as any);
  }, []);

  // ===== 통계 카드 계산 =====
  const computeStats = useCallback((data: Quote[]): StatCard[] => {
    const now = new Date();
    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const startOfWeek = new Date(now);
    startOfWeek.setDate(now.getDate() - now.getDay());

    const thisMonthQuotes = data.filter(
      (q) => new Date(q.registrationDate) >= startOfMonth
    );
    const thisMonthAmount = thisMonthQuotes.reduce((sum, q) => sum + q.totalAmount, 0);

    const ongoingQuotes = data.filter((q) => q.status === 'draft');
    const ongoingAmount = ongoingQuotes.reduce((sum, q) => sum + q.totalAmount, 0);

    const thisWeekQuotes = data.filter(
      (q) => new Date(q.registrationDate) >= startOfWeek
    );

    const thisMonthConvertedCount = thisMonthQuotes.filter(
      (q) => q.status === 'converted'
    ).length;
    const thisMonthConversionRate =
      thisMonthQuotes.length > 0
        ? ((thisMonthConvertedCount / thisMonthQuotes.length) * 100).toFixed(1)
        : '0.0';

    return [
      {
        label: '이번 달 견적 금액',
        value: formatAmountManwon(thisMonthAmount),
        icon: Calculator,
        iconColor: 'text-blue-600',
      },
      {
        label: '진행중 견적 금액',
        value: formatAmountManwon(ongoingAmount),
        icon: FileText,
        iconColor: 'text-orange-600',
      },
      {
        label: '이번 주 신규 견적',
        value: `${thisWeekQuotes.length}건`,
        icon: Edit,
        iconColor: 'text-green-600',
      },
      {
        label: '이번 달 수주 전환율',
        value: `${thisMonthConversionRate}%`,
        icon: CheckCircle,
        iconColor: 'text-purple-600',
      },
    ];
  }, []);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Quote> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '견적 목록',
      description: '견적서 작성 및 관리',
      icon: FileText,
      basePath: '/sales/quote-management',

      // ID 추출
      idField: 'id',
      getItemId: (item: Quote) => item.id,

      // API 액션
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getQuotes({
              page: params?.page || 1,
              perPage: 9999, // 클라이언트 사이드 필터링: 전체 데이터 로드
              search: params?.search || undefined,
            });

            if (result.success) {
              setAllQuotes(result.data);
              return {
                success: true,
                data: result.data,
                totalCount: result.data.length,
                totalPages: 1,
              };
            }
            return { success: false, error: result.error || '데이터 조회에 실패했습니다.' };
          } catch {
            return { success: false, error: '서버 오류가 발생했습니다.' };
          }
        },
        deleteItem: async (id: string) => {
          const result = await deleteQuote(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await bulkDeleteQuotes(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
        { key: 'quoteNumber', label: '견적번호', className: 'min-w-[120px]', sortable: true, copyable: true },
        { key: 'registrationDate', label: '접수일', className: 'w-[100px]', sortable: true, copyable: true },
        { key: 'status', label: '상태', className: 'w-[80px]', sortable: true },
        { key: 'productCategory', label: '제품분류', className: 'w-[100px]', sortable: true, copyable: true },
        { key: 'quantity', label: '수량', className: 'w-[60px] text-center', sortable: true, copyable: true },
        { key: 'totalAmount', label: '금액', className: 'w-[120px] text-right', sortable: true, copyable: true },
        { key: 'clientName', label: '발주처', className: 'min-w-[100px]', sortable: true, copyable: true },
        { key: 'siteName', label: '현장명', className: 'min-w-[120px]', sortable: true, copyable: true },
        { key: 'managerName', label: '담당자', className: 'w-[80px]', sortable: true, copyable: true },
        { key: 'description', label: '비고', className: 'min-w-[150px]', copyable: true },
        { key: 'actions', label: '작업', className: 'w-[100px]' },
      ],

      // 클라이언트 사이드 필터링
      clientSideFiltering: true,
      itemsPerPage: 20,

      // 필터링 함수 (날짜 + 제품분류 + 상태)
      customFilterFn: (items: Quote[]) => {
        return items.filter((item) => {
          // 날짜 필터
          const itemDate = item.registrationDate;
          if (itemDate) {
            if (startDate && itemDate < startDate) return false;
            if (endDate && itemDate > endDate) return false;
          }

          // 제품분류 필터
          if (productCategoryFilter !== 'all') {
            const category = item.productCategory as string;
            if (productCategoryFilter === 'STEEL' && category !== 'STEEL') return false;
            if (productCategoryFilter === 'SCREEN' && category !== 'SCREEN') return false;
            if (productCategoryFilter === 'MIXED' && category !== 'MIXED') return false;
          }

          // 상태 필터
          if (statusFilter !== 'all') {
            if (statusFilter === 'initial') {
              // 최초작성: currentRevision === 0 && !isFinal
              if (!(item.currentRevision === 0 && !item.isFinal)) return false;
            }
            if (statusFilter === 'revising') {
              // N차수정: currentRevision > 0 && !isFinal
              if (!(item.currentRevision > 0 && !item.isFinal)) return false;
            }
            if (statusFilter === 'final') {
              // 최종확정: isFinal === true
              if (!item.isFinal) return false;
            }
          }

          return true;
        });
      },

      // 검색 필터 함수
      searchFilter: (item: Quote, searchValue: string) => {
        const search = searchValue.toLowerCase();
        return (
          (item.quoteNumber?.toLowerCase() || '').includes(search) ||
          (item.clientName?.toLowerCase() || '').includes(search) ||
          (item.managerName?.toLowerCase() || '').includes(search) ||
          (item.siteCode?.toLowerCase() || '').includes(search) ||
          (item.siteName?.toLowerCase() || '').includes(search)
        );
      },

      // 커스텀 정렬 (최신순)
      customSortFn: (items: Quote[]) => {
        return [...items].sort((a, b) =>
          new Date(b.registrationDate).getTime() - new Date(a.registrationDate).getTime()
        );
      },

      // 탭 비활성화 (필터로 대체)
      tabs: [],

      // 통계 카드
      computeStats,

      // 테이블 우측 필터 (탭 영역에 표시)
      tableHeaderActions: (
        <div className="flex items-center gap-2">
          {/* 제품분류 필터 */}
          <Select value={productCategoryFilter} onValueChange={setProductCategoryFilter}>
            <SelectTrigger className="min-w-[100px] w-auto">
              <SelectValue placeholder="제품분류" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">제품분류: 전체</SelectItem>
              <SelectItem value="STEEL">제품분류: 철재</SelectItem>
              <SelectItem value="SCREEN">제품분류: 스크린</SelectItem>
            </SelectContent>
          </Select>

          {/* 상태 필터 */}
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="min-w-[100px] w-auto">
              <SelectValue placeholder="상태" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">상태: 전체</SelectItem>
              <SelectItem value="initial">상태: 최초작성</SelectItem>
              <SelectItem value="revising">상태: N차수정</SelectItem>
              <SelectItem value="final">상태: 견적완료</SelectItem>
            </SelectContent>
          </Select>
        </div>
      ),

      // 날짜 필터
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 검색
      searchPlaceholder: '견적번호, 발주처, 담당자, 현장코드, 현장명 검색...',

      // 헤더 액션
      headerActions: () => (
        <Button
          className="ml-auto"
          onClick={() => router.push('/sales/quote-management/new?mode=new')}
        >
          <FileText className="w-4 h-4 mr-2" />
          견적 등록
        </Button>
      ),

      // 일괄 삭제 핸들러
      onBulkDelete: deleteDialog.bulk.open,

      // 테이블 행 렌더링
      renderTableRow: (
        quote: Quote,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Quote>
      ) => {
        return (
          <TableRow
            key={quote.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-50' : ''}`}
            onClick={() => handleView(quote)}
          >
            <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
              <Checkbox
                checked={handlers.isSelected}
                onCheckedChange={handlers.onToggle}
              />
            </TableCell>
            <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell>
              <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
                {quote.quoteNumber || '-'}
              </code>
            </TableCell>
            <TableCell>{quote.registrationDate}</TableCell>
            <TableCell>{getRevisionBadge(quote)}</TableCell>
            <TableCell>
              <Badge variant="outline">
                {PRODUCT_CATEGORY_LABELS[quote.productCategory] || quote.productCategory}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{quote.quantity}</TableCell>
            <TableCell className="text-right">{formatAmount(quote.totalAmount)}</TableCell>
            <TableCell>{quote.clientName}</TableCell>
            <TableCell>
              <div className="flex flex-col gap-1">
                <span>{quote.siteName || '-'}</span>
                {quote.siteCode && (
                  <code className="inline-block w-fit text-xs bg-gray-100 text-gray-700 px-1.5 py-0.5 rounded font-mono whitespace-nowrap">
                    {quote.siteCode}
                  </code>
                )}
              </div>
            </TableCell>
            <TableCell>{quote.managerName || '-'}</TableCell>
            <TableCell>
              <div className="max-w-[200px] line-clamp-2 text-sm">
                {quote.description || '-'}
              </div>
            </TableCell>
            <TableCell onClick={(e) => e.stopPropagation()}>
              {handlers.isSelected && (
                <div className="flex gap-1">
                  {quote.currentRevision > 0 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewHistory(quote)}
                    >
                      <History className="h-4 w-4" />
                    </Button>
                  )}
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleEdit(quote)}
                  >
                    <Edit className="h-4 w-4" />
                  </Button>
                  {!quote.isFinal && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => deleteDialog.single.open(quote.id)}
                      disabled={deleteDialog.isPending}
                    >
                      <Trash2 className="h-4 w-4 text-red-500" />
                    </Button>
                  )}
                </div>
              )}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        quote: Quote,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Quote>
      ) => {
        return (
          <ListMobileCard
            key={quote.id}
            id={quote.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleView(quote)}
            headerBadges={
              <>
                <Badge
                  variant="outline"
                  className="bg-gray-100 text-gray-700 font-mono text-xs"
                >
                  {globalIndex}
                </Badge>
                <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
                  {quote.quoteNumber}
                </code>
              </>
            }
            title={quote.clientName}
            statusBadge={getRevisionBadge(quote)}
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="현장명" value={quote.siteName || '-'} />
                <InfoField label="현장코드" value={quote.siteCode || '-'} />
                <InfoField label="접수일" value={quote.registrationDate} />
                <InfoField label="담당자" value={quote.managerName || '-'} />
                <InfoField
                  label="제품분류"
                  value={PRODUCT_CATEGORY_LABELS[quote.productCategory] || quote.productCategory}
                />
                <InfoField label="수량" value={`${quote.quantity}개`} />
                <InfoField
                  label="총 금액"
                  value={formatAmount(quote.totalAmount)}
                  valueClassName="text-green-600"
                />
              </div>
            }
            actions={
              handlers.isSelected ? (
                <div className="flex gap-2 flex-wrap">
                  {quote.currentRevision > 0 && (
                    <Button
                      variant="outline"
                      size="default"
                      className="flex-1 min-w-[100px] h-11"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleViewHistory(quote);
                      }}
                    >
                      <History className="h-4 w-4 mr-2" />
                      이력
                    </Button>
                  )}
                  <Button
                    variant="default"
                    size="default"
                    className="flex-1 min-w-[100px] h-11"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEdit(quote);
                    }}
                  >
                    <Edit className="h-4 w-4 mr-2" />
                    수정
                  </Button>
                  {!quote.isFinal && (
                    <Button
                      variant="outline"
                      size="default"
                      className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
                      onClick={(e) => {
                        e.stopPropagation();
                        deleteDialog.single.open(quote.id);
                      }}
                      disabled={deleteDialog.isPending}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      삭제
                    </Button>
                  )}
                </div>
              ) : undefined
            }
          />
        );
      },
    }),
    [computeStats, router, handleView, handleEdit, handleViewHistory, getRevisionBadge, deleteDialog, startDate, endDate, productCategoryFilter, statusFilter]
  );

  return (
    <>
      <UniversalListPage config={config} initialData={initialData} />

      {/* 산출내역서 다이얼로그 */}
      <StandardDialog
        open={isCalculationDialogOpen}
        onOpenChange={setIsCalculationDialogOpen}
        title="산출내역서"
        description={
          calculationQuote
            ? `견적번호: ${calculationQuote.quoteNumber} | 발주처: ${calculationQuote.clientName}`
            : ''
        }
        size="xl"
        footer={
          <Button onClick={() => setIsCalculationDialogOpen(false)}>닫기</Button>
        }
      >
        {calculationQuote && (
          <div className="space-y-6">
            {/* 기본 정보 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-muted/50 rounded-lg">
              <div>
                <p className="text-sm text-muted-foreground">견적번호</p>
                <p className="font-medium">{calculationQuote.quoteNumber}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">발주처</p>
                <p className="font-medium">{calculationQuote.clientName}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">현장명</p>
                <p className="font-medium">{calculationQuote.siteName || '-'}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">접수일</p>
                <p className="font-medium">{calculationQuote.registrationDate}</p>
              </div>
            </div>

            <Separator />

            {/* 산출 내역 테이블 */}
            <div>
              <h4 className="font-semibold mb-3 flex items-center gap-2">
                <Calculator className="w-5 h-5" />
                산출 내역
              </h4>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[60px]">번호</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead>규격</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                      <TableHead className="text-right">단가</TableHead>
                      <TableHead className="text-right">공급가</TableHead>
                      <TableHead className="text-right">부가세</TableHead>
                      <TableHead className="text-right">합계</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {calculationQuote.items.length > 0 ? (
                      calculationQuote.items.map((item, idx) => (
                        <TableRow key={item.id}>
                          <TableCell>{idx + 1}</TableCell>
                          <TableCell>{item.productName}</TableCell>
                          <TableCell>{item.specification || '-'}</TableCell>
                          <TableCell className="text-center">{item.quantity}</TableCell>
                          <TableCell className="text-right">
                            {formatAmount(item.unitPrice)}원
                          </TableCell>
                          <TableCell className="text-right">
                            {formatAmount(item.supplyAmount)}원
                          </TableCell>
                          <TableCell className="text-right">
                            {formatAmount(item.taxAmount)}원
                          </TableCell>
                          <TableCell className="text-right font-medium">
                            {formatAmount(item.totalAmount)}원
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell>1</TableCell>
                        <TableCell>
                          {PRODUCT_CATEGORY_LABELS[calculationQuote.productCategory]}
                        </TableCell>
                        <TableCell>-</TableCell>
                        <TableCell className="text-center">
                          {calculationQuote.quantity}
                        </TableCell>
                        <TableCell className="text-right">
                          {formatAmount(
                            Math.floor(calculationQuote.totalAmount / calculationQuote.quantity)
                          )}
                          원
                        </TableCell>
                        <TableCell className="text-right">
                          {formatAmount(calculationQuote.supplyAmount)}원
                        </TableCell>
                        <TableCell className="text-right">
                          {formatAmount(calculationQuote.taxAmount)}원
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          {formatAmount(calculationQuote.totalAmount)}원
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </div>

            {/* 합계 */}
            <div className="bg-muted/50 p-4 rounded-lg">
              <div className="flex justify-between items-center">
                <span className="font-semibold">총 금액</span>
                <span className="text-xl font-bold text-primary">
                  {formatAmount(calculationQuote.totalAmount)}원
                </span>
              </div>
            </div>
          </div>
        )}
      </StandardDialog>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteDialog.single.isOpen}
        onOpenChange={deleteDialog.single.onOpenChange}
        description={
          <>
            {deleteDialog.single.targetId
              ? `견적번호: ${allQuotes.find((q) => q.id === deleteDialog.single.targetId)?.quoteNumber || deleteDialog.single.targetId}`
              : ''}
            <br />
            이 견적을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.
          </>
        }
        loading={deleteDialog.isPending}
        onConfirm={deleteDialog.single.confirm}
      />

      {/* 일괄 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteDialog.bulk.isOpen}
        onOpenChange={deleteDialog.bulk.onOpenChange}
        description={`선택한 ${deleteDialog.bulk.ids.length}개의 견적을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.`}
        loading={deleteDialog.isPending}
        onConfirm={deleteDialog.bulk.confirm}
      />
    </>
  );
}
