import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { 
  FileText, 
  Save, 
  Send,
  Plus,
  X,
  User,
  Calendar,
  Building,
  FileSignature
} from 'lucide-react';

export function DocumentWrite() {
  const [documentType, setDocumentType] = useState('');
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [approvers, setApprovers] = useState<string[]>(['']);
  const [references, setReferences] = useState<string[]>(['']);

  const documentTypes = [
    '품의서',
    '계획서',
    '보고서',
    '제안서',
    '신청서',
    '계약서',
    '협조요청서',
    '기타'
  ];

  const departments = [
    '생산팀',
    '품질팀',
    '자재팀',
    '구매팀',
    '영업팀',
    '재무팀',
    '인사팀',
    '개발팀'
  ];

  const addApprover = () => {
    setApprovers([...approvers, '']);
  };

  const removeApprover = (index: number) => {
    setApprovers(approvers.filter((_, i) => i !== index));
  };

  const updateApprover = (index: number, value: string) => {
    const newApprovers = [...approvers];
    newApprovers[index] = value;
    setApprovers(newApprovers);
  };

  const addReference = () => {
    setReferences([...references, '']);
  };

  const removeReference = (index: number) => {
    setReferences(references.filter((_, i) => i !== index));
  };

  const updateReference = (index: number, value: string) => {
    const newReferences = [...references];
    newReferences[index] = value;
    setReferences(newReferences);
  };

  const handleSaveDraft = () => {
    alert('임시 저장되었습니다.');
  };

  const handleSubmit = () => {
    if (!documentType || !title || !content) {
      alert('필수 항목을 모두 입력해주세요.');
      return;
    }
    alert('문서가 제출되었습니다.');
  };

  return (
    <div className="p-6 space-y-6">
      <div>
        <h1 className="mb-2">문서 작성</h1>
        <p className="text-muted-foreground">
          새로운 결재 문서를 작성합니다.
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 문서 작성 영역 */}
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>기본 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="documentType">문서 유형 *</Label>
                  <Select value={documentType} onValueChange={setDocumentType}>
                    <SelectTrigger id="documentType">
                      <SelectValue placeholder="문서 유형 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {documentTypes.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="documentDate">작성일</Label>
                  <Input
                    id="documentDate"
                    type="date"
                    defaultValue={new Date().toISOString().split('T')[0]}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="title">제목 *</Label>
                <Input
                  id="title"
                  placeholder="문서 제목을 입력하세요"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="department">기안 부서</Label>
                <Select>
                  <SelectTrigger id="department">
                    <SelectValue placeholder="부서 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {departments.map((dept) => (
                      <SelectItem key={dept} value={dept}>
                        {dept}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>문서 내용</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="content">내용 *</Label>
                <Textarea
                  id="content"
                  placeholder="문서 내용을 입력하세요"
                  value={content}
                  onChange={(e) => setContent(e.target.value)}
                  rows={15}
                  className="resize-none"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="attachment">첨부파일</Label>
                <Input id="attachment" type="file" multiple />
                <p className="text-sm text-muted-foreground">
                  최대 10MB, 최대 5개 파일
                </p>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 결재선 및 참조 영역 */}
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>결재선</CardTitle>
                <Button size="sm" variant="outline" onClick={addApprover}>
                  <Plus className="h-4 w-4 mr-1" />
                  추가
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              {approvers.map((approver, index) => (
                <div key={index} className="flex items-center gap-2">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
                      <User className="h-3 w-3" />
                      결재자 {index + 1}
                    </div>
                    <Select value={approver} onValueChange={(value) => updateApprover(index, value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="결재자 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="팀장">팀장</SelectItem>
                        <SelectItem value="부장">부장</SelectItem>
                        <SelectItem value="이사">이사</SelectItem>
                        <SelectItem value="본부장">본부장</SelectItem>
                        <SelectItem value="대표이사">대표이사</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  {approvers.length > 1 && (
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => removeApprover(index)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>참조</CardTitle>
                <Button size="sm" variant="outline" onClick={addReference}>
                  <Plus className="h-4 w-4 mr-1" />
                  추가
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              {references.map((reference, index) => (
                <div key={index} className="flex items-center gap-2">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 text-sm text-muted-foreground mb-1">
                      <User className="h-3 w-3" />
                      참조자 {index + 1}
                    </div>
                    <Select value={reference} onValueChange={(value) => updateReference(index, value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="참조자 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {departments.map((dept) => (
                          <SelectItem key={dept} value={dept}>
                            {dept}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  {references.length > 1 && (
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => removeReference(index)}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                </div>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>문서 정보</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center gap-2 text-sm">
                <Building className="h-4 w-4 text-muted-foreground" />
                <span className="text-muted-foreground">기안부서:</span>
                <span>생산팀</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <User className="h-4 w-4 text-muted-foreground" />
                <span className="text-muted-foreground">기안자:</span>
                <span>김철수</span>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-muted-foreground">작성일:</span>
                <span>{new Date().toLocaleDateString('ko-KR')}</span>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* 하단 버튼 */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col md:flex-row gap-4 justify-end">
            <Button variant="outline" onClick={handleSaveDraft}>
              <Save className="h-4 w-4 mr-2" />
              임시저장
            </Button>
            <Button onClick={handleSubmit}>
              <Send className="h-4 w-4 mr-2" />
              결재요청
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
