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 { 
  FileText, 
  Eye, 
  Download,
  CheckCircle,
  Clock,
  XCircle
} from 'lucide-react';

interface ReferenceDocument {
  id: string;
  title: string;
  type: string;
  requester: string;
  referenceDate: string;
  status: '진행중' | '승인완료' | '반려';
  approver: string;
}

export function ReferenceBox() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('전체');

  // 모의 데이터
  const referenceDocuments: ReferenceDocument[] = [
    {
      id: 'REF-001',
      title: '2025년 품질 개선 계획',
      type: '계획서',
      requester: '품질팀 정수진',
      referenceDate: '2025-10-20',
      status: '진행중',
      approver: '생산본부장'
    },
    {
      id: 'REF-002',
      title: '설비 유지보수 일정표',
      type: '일정표',
      requester: '설비팀 강민호',
      referenceDate: '2025-10-19',
      status: '승인완료',
      approver: '공장장'
    },
    {
      id: 'REF-003',
      title: '안전교육 실시 계획',
      type: '계획서',
      requester: '안전팀 송지은',
      referenceDate: '2025-10-18',
      status: '승인완료',
      approver: '총무이사'
    },
    {
      id: 'REF-004',
      title: 'ISO 인증 갱신 보고',
      type: '보고서',
      requester: '품질팀 이현우',
      referenceDate: '2025-10-17',
      status: '진행중',
      approver: '대표이사'
    },
    {
      id: 'REF-005',
      title: '신제품 개발 제안',
      type: '제안서',
      requester: '개발팀 박준영',
      referenceDate: '2025-10-16',
      status: '반려',
      approver: '연구소장'
    },
  ];

  const statuses = ['전체', '진행중', '승인완료', '반려'];

  const filteredDocuments = referenceDocuments.filter(doc => {
    const matchesSearch = doc.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         doc.requester.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === '전체' || doc.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const totalDocs = referenceDocuments.length;
  const inProgress = referenceDocuments.filter(d => d.status === '진행중').length;
  const approved = referenceDocuments.filter(d => d.status === '승인완료').length;
  const rejected = referenceDocuments.filter(d => d.status === '반려').length;

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

  const handleDownload = (id: string) => {
    console.log('다운로드:', id);
  };

  const columns: Column<ReferenceDocument>[] = [
    {
      key: 'id',
      label: '문서번호'
    },
    {
      key: 'title',
      label: '제목'
    },
    {
      key: 'type',
      label: '문서종류'
    },
    {
      key: 'requester',
      label: '기안자'
    },
    {
      key: 'approver',
      label: '결재자'
    },
    {
      key: 'referenceDate',
      label: '참조일'
    },
    {
      key: 'status',
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '진행중' ? 'default' : status === '승인완료' ? 'outline' : 'destructive';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    {
      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" variant="outline" onClick={() => handleDownload(row.id)}>
            <Download className="w-4 h-4" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <ListPageTemplate
      title="참조함"
      description="참조된 문서를 확인합니다"
      icon={FileText}
      stats={[
        {
          label: "전체 문서",
          value: `${totalDocs}건`,
          icon: FileText,
          iconColor: "text-blue-600",
          description: "참조 문서"
        },
        {
          label: "진행중",
          value: `${inProgress}건`,
          icon: Clock,
          iconColor: "text-orange-600",
          description: "결재 진행중"
        },
        {
          label: "승인완료",
          value: `${approved}건`,
          icon: CheckCircle,
          iconColor: "text-green-600",
          description: "승인된 문서"
        },
        {
          label: "반려",
          value: `${rejected}건`,
          icon: XCircle,
          iconColor: "text-red-600",
          description: "반려된 문서"
        }
      ]}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="제목, 기안자 검색..."
      extraActions={
        <Select value={selectedStatus} onValueChange={setSelectedStatus}>
          <SelectTrigger className="w-[150px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {statuses.map(status => (
              <SelectItem key={status} value={status}>{status}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      }
      data={filteredDocuments}
      keyField="id"
      columns={columns}
      renderMobileCard={(doc) => ({
        title: doc.title,
        subtitle: `${doc.id} | ${doc.type}`,
        badge: {
          label: doc.status,
          variant: doc.status === '진행중' ? 'default' : doc.status === '승인완료' ? 'outline' : 'destructive'
        },
        fields: [
          {
            label: "기안자",
            value: doc.requester
          },
          {
            label: "결재자",
            value: doc.approver
          },
          {
            label: "참조일",
            value: doc.referenceDate
          }
        ],
        actions: [
          {
            label: "상세보기",
            icon: Eye,
            onClick: () => handleView(doc.id)
          },
          {
            label: "다운로드",
            icon: Download,
            onClick: () => handleDownload(doc.id)
          }
        ]
      })}
      emptyIcon={FileText}
      emptyTitle="참조 문서가 없습니다"
      emptyDescription="참조된 문서가 없습니다"
    />
  );
}
