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, 
  Edit, 
  Trash2,
  Clock,
  AlertCircle
} from 'lucide-react';

interface DraftDocument {
  id: string;
  title: string;
  type: string;
  createdDate: string;
  status: '임시저장' | '작성중';
  content: string;
}

export function DraftBox() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('전체');

  // 모의 데이터
  const draftDocuments: DraftDocument[] = [
    {
      id: 'DRAFT-001',
      title: '2025년 1분기 생산 계획서',
      type: '계획서',
      createdDate: '2025-10-20',
      status: '임시저장',
      content: '1분기 생산 계획에 대한 내용...'
    },
    {
      id: 'DRAFT-002',
      title: '원자재 구매 품의서',
      type: '품의서',
      createdDate: '2025-10-19',
      status: '작성중',
      content: '원자재 구매에 대한 품의...'
    },
    {
      id: 'DRAFT-003',
      title: '설비 투자 검토 보고서',
      type: '보고서',
      createdDate: '2025-10-18',
      status: '임시저장',
      content: '신규 설비 투자에 대한 검토...'
    },
    {
      id: 'DRAFT-004',
      title: '휴가 신청서',
      type: '신청서',
      createdDate: '2025-10-17',
      status: '작성중',
      content: '연차 휴가 신청...'
    },
  ];

  const documentTypes = ['전체', '계획서', '품의서', '보고서', '신청서'];

  const filteredDocuments = draftDocuments.filter(doc => {
    const matchesSearch = doc.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         doc.id.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = selectedType === '전체' || doc.type === selectedType;
    return matchesSearch && matchesType;
  });

  const totalDrafts = draftDocuments.length;
  const inProgress = draftDocuments.filter(d => d.status === '작성중').length;
  const saved = draftDocuments.filter(d => d.status === '임시저장').length;

  const handleEdit = (id: string) => {
    console.log('수정:', id);
  };

  const handleDelete = (id: string) => {
    if (confirm('정말 삭제하시겠습니까?')) {
      console.log('삭제:', id);
    }
  };

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

  const columns: Column<DraftDocument>[] = [
    {
      key: 'id',
      label: '문서번호'
    },
    {
      key: 'title',
      label: '제목'
    },
    {
      key: 'type',
      label: '문서종류'
    },
    {
      key: 'createdDate',
      label: '작성일'
    },
    {
      key: 'status',
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '작성중' ? 'default' : 'secondary';
        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" onClick={() => handleEdit(row.id)}>
            <Edit className="w-4 h-4" />
          </Button>
          <Button size="sm" variant="destructive" onClick={() => handleDelete(row.id)}>
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <ListPageTemplate
      title="기안함"
      description="작성 중이거나 임시 저장된 문서를 관리합니다"
      icon={FileText}
      stats={[
        {
          label: "전체 문서",
          value: `${totalDrafts}건`,
          icon: FileText,
          iconColor: "text-blue-600",
          description: "임시 저장 문서"
        },
        {
          label: "작성중",
          value: `${inProgress}건`,
          icon: Clock,
          iconColor: "text-orange-600",
          description: "진행중"
        },
        {
          label: "임시저장",
          value: `${saved}건`,
          icon: AlertCircle,
          iconColor: "text-gray-600",
          description: "저장된 문서"
        }
      ]}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="제목, 문서번호 검색..."
      extraActions={
        <Select value={selectedType} onValueChange={setSelectedType}>
          <SelectTrigger className="w-[150px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {documentTypes.map(type => (
              <SelectItem key={type} value={type}>{type}</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' : 'secondary'
        },
        fields: [
          {
            label: "작성일",
            value: doc.createdDate
          },
          {
            label: "내용 미리보기",
            value: doc.content.substring(0, 50) + '...'
          }
        ],
        actions: [
          {
            label: "상세보기",
            icon: Eye,
            onClick: () => handleView(doc.id)
          },
          {
            label: "수정",
            icon: Edit,
            onClick: () => handleEdit(doc.id)
          },
          {
            label: "삭제",
            icon: Trash2,
            onClick: () => handleDelete(doc.id),
            variant: "destructive"
          }
        ]
      })}
      emptyIcon={FileText}
      emptyTitle="임시 저장된 문서가 없습니다"
      emptyDescription="작성 중인 문서가 없습니다"
    />
  );
}
