import React, { useState } from 'react';
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from './organisms/DataTable';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { 
  FileCheck, 
  Eye, 
  CheckCircle,
  XCircle,
  Clock,
  AlertCircle
} from 'lucide-react';

interface ApprovalDocument {
  id: string;
  title: string;
  type: string;
  requester: string;
  requestDate: string;
  priority: '긴급' | '보통' | '낮음';
  status: '대기' | '검토중';
  daysLeft: number;
}

export function ApprovalBox() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPriority, setSelectedPriority] = useState('전체');

  // 모의 데이터
  const approvalDocuments: ApprovalDocument[] = [
    {
      id: 'APP-001',
      title: '신규 생산설비 도입 승인 요청',
      type: '품의서',
      requester: '생산팀 김철수',
      requestDate: '2025-10-21',
      priority: '긴급',
      status: '대기',
      daysLeft: 1
    },
    {
      id: 'APP-002',
      title: '2025년 2분기 예산안',
      type: '계획서',
      requester: '재무팀 이영희',
      requestDate: '2025-10-20',
      priority: '보통',
      status: '검토중',
      daysLeft: 3
    },
    {
      id: 'APP-003',
      title: '외주 협력업체 계약서',
      type: '계약서',
      requester: '구매팀 박민수',
      requestDate: '2025-10-19',
      priority: '보통',
      status: '대기',
      daysLeft: 2
    },
    {
      id: 'APP-004',
      title: '품질 개선 프로젝트 제안',
      type: '제안서',
      requester: '품질팀 정수진',
      requestDate: '2025-10-18',
      priority: '낮음',
      status: '대기',
      daysLeft: 5
    },
    {
      id: 'APP-005',
      title: '원자재 긴급 구매 요청',
      type: '구매요청서',
      requester: '자재팀 최동훈',
      requestDate: '2025-10-21',
      priority: '긴급',
      status: '대기',
      daysLeft: 1
    },
  ];

  const priorities = ['전체', '긴급', '보통', '낮음'];

  const filteredDocuments = approvalDocuments.filter(doc => {
    const matchesSearch = doc.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         doc.requester.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesPriority = selectedPriority === '전체' || doc.priority === selectedPriority;
    return matchesSearch && matchesPriority;
  });

  const totalDocs = approvalDocuments.length;
  const urgentDocs = approvalDocuments.filter(d => d.priority === '긴급').length;
  const waitingDocs = approvalDocuments.filter(d => d.status === '대기').length;
  const reviewingDocs = approvalDocuments.filter(d => d.status === '검토중').length;

  const handleApprove = (id: string) => {
    console.log('승인:', id);
  };

  const handleReject = (id: string) => {
    console.log('반려:', id);
  };

  const handleView = (id: string) => {
    console.log('상세보기:', id);
  };

  const columns: Column<ApprovalDocument>[] = [
    {
      key: 'id',
      label: '문서번호'
    },
    {
      key: 'title',
      label: '제목'
    },
    {
      key: 'type',
      label: '문서종류'
    },
    {
      key: 'requester',
      label: '기안자'
    },
    {
      key: 'requestDate',
      label: '기안일'
    },
    {
      key: 'priority',
      label: '우선순위',
      render: (value) => {
        const priority = value as string;
        const variant = priority === '긴급' ? 'destructive' : priority === '보통' ? 'default' : 'secondary';
        return <Badge variant={variant}>{priority}</Badge>;
      }
    },
    {
      key: 'status',
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '대기' ? 'secondary' : 'default';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    {
      key: 'daysLeft',
      label: '잔여일',
      render: (value) => {
        const days = value as number;
        return (
          <span className={days <= 1 ? 'text-red-600 font-semibold' : ''}>
            {days}일
          </span>
        );
      }
    },
    {
      key: 'actions',
      label: '액션',
      render: (_, row) => (
        <div className="flex gap-2">
          <Button size="sm" variant="outline" onClick={() => handleView(row.id)}>
            <Eye className="w-4 h-4" />
          </Button>
          <Button size="sm" onClick={() => handleApprove(row.id)}>
            <CheckCircle className="w-4 h-4" />
          </Button>
          <Button size="sm" variant="destructive" onClick={() => handleReject(row.id)}>
            <XCircle className="w-4 h-4" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <ListPageTemplate
      title="결재함"
      description="승인이 필요한 문서를 확인하고 결재합니다"
      icon={FileCheck}
      stats={[
        {
          label: "전체 문서",
          value: `${totalDocs}건`,
          icon: FileCheck,
          iconColor: "text-blue-600",
          description: "승인 대기"
        },
        {
          label: "긴급",
          value: `${urgentDocs}건`,
          icon: AlertCircle,
          iconColor: "text-red-600",
          description: "우선 처리 필요"
        },
        {
          label: "대기중",
          value: `${waitingDocs}건`,
          icon: Clock,
          iconColor: "text-orange-600",
          description: "승인 대기"
        },
        {
          label: "검토중",
          value: `${reviewingDocs}건`,
          icon: Eye,
          iconColor: "text-green-600",
          description: "검토 진행중"
        }
      ]}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="제목, 기안자 검색..."
      extraActions={
        <Select value={selectedPriority} onValueChange={setSelectedPriority}>
          <SelectTrigger className="w-[150px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {priorities.map(priority => (
              <SelectItem key={priority} value={priority}>{priority}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      }
      data={filteredDocuments}
      keyField="id"
      columns={columns}
      renderMobileCard={(doc) => ({
        title: doc.title,
        subtitle: `${doc.id} | ${doc.type}`,
        badge: {
          label: doc.priority,
          variant: doc.priority === '긴급' ? 'destructive' : doc.priority === '보통' ? 'default' : 'secondary'
        },
        fields: [
          {
            label: "기안자",
            value: doc.requester
          },
          {
            label: "기안일",
            value: doc.requestDate
          },
          {
            label: "상태",
            value: doc.status
          },
          {
            label: "잔여일",
            value: `${doc.daysLeft}일`,
            className: doc.daysLeft <= 1 ? 'text-red-600 font-semibold' : ''
          }
        ],
        actions: [
          {
            label: "상세보기",
            icon: Eye,
            onClick: () => handleView(doc.id)
          },
          {
            label: "승인",
            icon: CheckCircle,
            onClick: () => handleApprove(doc.id)
          },
          {
            label: "반려",
            icon: XCircle,
            onClick: () => handleReject(doc.id),
            variant: "destructive"
          }
        ]
      })}
      emptyIcon={FileCheck}
      emptyTitle="결재할 문서가 없습니다"
      emptyDescription="승인 대기중인 문서가 없습니다"
    />
  );
}
