import { MobileCard } from "../organisms/MobileCard";
import { SearchFilter } from "../organisms/SearchFilter";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from "../ui/pagination";
import { Badge } from "../ui/badge";
import { Edit, Eye, Trash2, FileText, CheckCircle, History, Calculator } from "lucide-react";

export interface QuoteListItem {
  id: string;
  quoteNumber: string;
  registrationDate: string;
  client: string;
  site?: string;
  manager?: string;
  contact?: string;
  productCode?: string;
  quantity?: number;
  amount: number;
  status?: 'draft' | 'sent' | 'approved' | 'rejected' | 'converted';
  currentRevision?: number;
  isFinal?: boolean;
  type?: string;
  remarks?: string;
}

export interface QuoteListTemplateProps {
  quotes: QuoteListItem[];
  searchValue: string;
  onSearchChange: (value: string) => void;
  filterStatus: string;
  onFilterChange: (value: string) => void;
  currentPage: number;
  onPageChange: (page: number) => void;
  itemsPerPage?: number;
  onQuoteClick?: (quote: QuoteListItem) => void;
  onEdit?: (quote: QuoteListItem) => void;
  onView?: (quote: QuoteListItem) => void;
  onDelete?: (quoteId: string) => void;
  onViewHistory?: (quote: QuoteListItem) => void;
  onViewCalculation?: (quote: QuoteListItem) => void;
  onFinalize?: (quoteId: string) => void;
  showActions?: boolean;
}

const statusLabels: Record<string, string> = {
  all: "전체",
  draft: "작성중",
  final: "최종확정",
  converted: "수주전환",
};

const statusBadgeVariants: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
  draft: "outline",
  final: "default",
  converted: "default",
};

export function QuoteListTemplate({
  quotes,
  searchValue,
  onSearchChange,
  filterStatus,
  onFilterChange,
  currentPage,
  onPageChange,
  itemsPerPage = 20,
  onQuoteClick,
  onEdit,
  onView,
  onDelete,
  onViewHistory,
  onViewCalculation,
  onFinalize,
  showActions = true,
}: QuoteListTemplateProps) {
  // 필터링된 견적
  const filteredQuotes = quotes.filter((quote) => {
    const matchesSearch =
      quote.quoteNumber.toLowerCase().includes(searchValue.toLowerCase()) ||
      quote.client.toLowerCase().includes(searchValue.toLowerCase()) ||
      (quote.manager && quote.manager.toLowerCase().includes(searchValue.toLowerCase())) ||
      (quote.productCode && quote.productCode.toLowerCase().includes(searchValue.toLowerCase())) ||
      (quote.site && quote.site.toLowerCase().includes(searchValue.toLowerCase())) ||
      (quote.remarks && quote.remarks.toLowerCase().includes(searchValue.toLowerCase()));

    let matchesStatus = true;
    if (filterStatus === "final") {
      matchesStatus = quote.isFinal === true;
    } else if (filterStatus === "draft") {
      matchesStatus = !quote.isFinal && quote.status !== 'converted';
    } else if (filterStatus === "converted") {
      matchesStatus = quote.status === 'converted';
    }

    return matchesSearch && matchesStatus;
  });

  // 페이징 처리
  const totalPages = Math.ceil(filteredQuotes.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedQuotes = filteredQuotes.slice(startIndex, endIndex);

  // 상태별 개수
  const statusCounts = {
    all: quotes.length,
    draft: quotes.filter(q => !q.isFinal && q.status !== 'converted').length,
    final: quotes.filter(q => q.isFinal).length,
    converted: quotes.filter(q => q.status === 'converted').length,
  };

  // 금액 포맷팅
  const formatAmount = (amount: number) => {
    return amount.toLocaleString('ko-KR');
  };

  // 상태 뱃지 생성
  const getStatusBadge = (quote: QuoteListItem) => {
    if (quote.status === 'converted') {
      return <Badge variant="default" className="bg-purple-600"><CheckCircle className="w-3 h-3 mr-1" />수주전환</Badge>;
    }
    if (quote.isFinal) {
      return <Badge variant="default" className="bg-green-600"><CheckCircle className="w-3 h-3 mr-1" />최종확정</Badge>;
    }
    if ((quote.currentRevision || 0) > 0) {
      return (
        <Badge variant="secondary" className="bg-orange-100 text-orange-700 border-orange-300">
          <History className="w-3 h-3 mr-1" />
          {quote.currentRevision}차 수정
        </Badge>
      );
    }
    return <Badge variant="outline" className="bg-gray-50">최초 작성</Badge>;
  };

  return (
    <div className="space-y-4">
      {/* 검색 및 필터 */}
      <div className="space-y-3">
        <SearchFilter
          searchValue={searchValue}
          onSearchChange={onSearchChange}
          searchPlaceholder="견적번호, 발주처, 담당자, 제품코드, 현장명으로 검색..."
          filterButton={false}
        />
        <Select value={filterStatus} onValueChange={onFilterChange}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="상태 필터" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">전체 ({statusCounts.all})</SelectItem>
            <SelectItem value="draft">작성중 ({statusCounts.draft})</SelectItem>
            <SelectItem value="final">최종확정 ({statusCounts.final})</SelectItem>
            <SelectItem value="converted">수주전환 ({statusCounts.converted})</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 견적 카드 목록 */}
      <div className="space-y-3">
        {paginatedQuotes.length === 0 ? (
          <div className="text-center py-12">
            <FileText className="w-12 h-12 mx-auto text-muted-foreground mb-3" />
            <p className="text-muted-foreground">
              {searchValue ? "검색 결과가 없습니다" : "견적이 없습니다"}
            </p>
          </div>
        ) : (
          paginatedQuotes.map((quote, index) => {
            const fields = [
              { label: "견적번호", value: quote.quoteNumber },
              { label: "접수일", value: quote.registrationDate || "-" },
              { label: "발주처", value: quote.client },
              { label: "현장명", value: quote.site || "-" },
              { label: "담당자", value: quote.manager || "-" },
              { label: "연락처", value: quote.contact || "-" },
              { label: "제품코드", value: quote.productCode || "-" },
              { label: "수량", value: `${quote.quantity || 0} EA` },
              { label: "금액", value: `₩${formatAmount(quote.amount || 0)}` },
            ];

            // 구분 추가
            if (quote.type) {
              fields.splice(2, 0, { label: "구분", value: quote.type, badge: true });
            }

            // 수정 이력 추가
            if ((quote.currentRevision || 0) > 0) {
              fields.push({
                label: "수정 차수",
                value: `${quote.currentRevision}차 수정`,
              });
            }

            // 비고 추가
            if (quote.remarks) {
              fields.push({
                label: "비고",
                value: quote.remarks,
              });
            }

            const actions = [];

            if (showActions) {
              if ((quote.currentRevision || 0) > 0 && onViewHistory) {
                actions.push({
                  label: "이력",
                  icon: History,
                  variant: "outline" as const,
                  onClick: () => onViewHistory(quote),
                });
              }
              if (onViewCalculation) {
                actions.push({
                  label: "산출",
                  icon: Calculator,
                  variant: "outline" as const,
                  onClick: () => onViewCalculation(quote),
                });
              }
              if (onView) {
                actions.push({
                  label: "상세",
                  icon: Eye,
                  variant: "outline" as const,
                  onClick: () => onView(quote),
                });
              }
              if (onEdit) {
                actions.push({
                  label: "수정",
                  icon: Edit,
                  variant: "outline" as const,
                  onClick: () => onEdit(quote),
                });
              }
              if (!quote.isFinal && onFinalize) {
                actions.push({
                  label: "확정",
                  icon: CheckCircle,
                  variant: "outline" as const,
                  onClick: () => onFinalize(quote.id),
                });
              }
              if (!quote.isFinal && onDelete) {
                actions.push({
                  label: "삭제",
                  icon: Trash2,
                  variant: "outline" as const,
                  onClick: () => onDelete(quote.id),
                });
              }
            }

            return (
              <div key={quote.id}>
                <MobileCard
                  icon={<FileText className="w-5 h-5 text-blue-600" />}
                  title={quote.quoteNumber}
                  subtitle={`#${filteredQuotes.length - (startIndex + index)}`}
                  badge={
                    quote.status === 'converted'
                      ? { label: "수주전환", variant: "default" }
                      : quote.isFinal
                      ? { label: "최종확정", variant: "default" }
                      : (quote.currentRevision || 0) > 0
                      ? { label: `${quote.currentRevision}차 수정`, variant: "secondary" }
                      : { label: "작성중", variant: "outline" }
                  }
                  fields={fields}
                  actions={actions.length > 0 ? actions : undefined}
                  onCardClick={onQuoteClick ? () => onQuoteClick(quote) : undefined}
                />
              </div>
            );
          })
        )}
      </div>

      {/* 페이지네이션 */}
      {totalPages > 1 && (
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                onClick={() => currentPage > 1 && onPageChange(currentPage - 1)}
                className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
              />
            </PaginationItem>
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNumber;
              if (totalPages <= 5) {
                pageNumber = i + 1;
              } else if (currentPage <= 3) {
                pageNumber = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNumber = totalPages - 4 + i;
              } else {
                pageNumber = currentPage - 2 + i;
              }

              return (
                <PaginationItem key={pageNumber}>
                  <PaginationLink
                    onClick={() => onPageChange(pageNumber)}
                    isActive={currentPage === pageNumber}
                    className="cursor-pointer"
                  >
                    {pageNumber}
                  </PaginationLink>
                </PaginationItem>
              );
            })}
            <PaginationItem>
              <PaginationNext
                onClick={() => currentPage < totalPages && onPageChange(currentPage + 1)}
                className={
                  currentPage === totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"
                }
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      )}

      {/* 결과 요약 */}
      <div className="text-center text-sm text-muted-foreground">
        총 {filteredQuotes.length}개 견적 중 {startIndex + 1}-
        {Math.min(endIndex, filteredQuotes.length)}개 표시
      </div>
    </div>
  );
}