'use client';

import { useSearchParams, useRouter } from 'next/navigation';
import { useState, useMemo, Suspense } from 'react';
import { FileText, ArrowLeft, Calendar, Clock, MapPin, FileCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { FormSectionSkeleton } from '@/components/ui/skeleton';
import { format } from 'date-fns';
import { toast } from 'sonner';

// 문서 유형 라벨
const DOCUMENT_TYPE_LABELS: Record<string, string> = {
  businessTripRequest: '출장신청',
  vacationRequest: '휴가신청',
  fieldWorkRequest: '외근신청',
  overtimeRequest: '연장근무신청',
};

// 문서 유형 아이콘
const DOCUMENT_TYPE_ICONS: Record<string, React.ElementType> = {
  businessTripRequest: MapPin,
  vacationRequest: Calendar,
  fieldWorkRequest: MapPin,
  overtimeRequest: Clock,
};

// 문서 유형 설명
const DOCUMENT_TYPE_DESCRIPTIONS: Record<string, string> = {
  businessTripRequest: '업무상 출장이 필요한 경우 작성합니다',
  vacationRequest: '연차, 병가 등 휴가 신청 시 작성합니다',
  fieldWorkRequest: '사업장 외 근무가 필요한 경우 작성합니다',
  overtimeRequest: '정규 근무시간 외 연장근무 시 작성합니다',
};

function DocumentNewContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const documentType = searchParams.get('type') || 'businessTripRequest';

  // 폼 상태
  const [formData, setFormData] = useState({
    title: '',
    startDate: format(new Date(), 'yyyy-MM-dd'),
    endDate: format(new Date(), 'yyyy-MM-dd'),
    startTime: '09:00',
    endTime: '18:00',
    destination: '',
    purpose: '',
    content: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 문서 유형 정보
  const typeInfo = useMemo(() => ({
    label: DOCUMENT_TYPE_LABELS[documentType] || '문서 등록',
    description: DOCUMENT_TYPE_DESCRIPTIONS[documentType] || '문서를 작성합니다',
    Icon: DOCUMENT_TYPE_ICONS[documentType] || FileText,
  }), [documentType]);

  // 입력 핸들러
  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 제출 핸들러
  const handleSubmit = async () => {
    setIsSubmitting(true);
    try {
      // TODO: 백엔드 API 구현 필요
      toast.success(`${typeInfo.label}이 등록되었습니다`);
      router.back();
    } catch (error) {
      console.error('Document creation error:', error);
      toast.error('문서 등록에 실패했습니다');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 취소 핸들러
  const handleCancel = () => {
    router.back();
  };

  return (
    <div className="container mx-auto py-6 max-w-2xl">
      {/* 헤더 */}
      <div className="mb-6">
        <Button
          variant="ghost"
          size="sm"
          onClick={handleCancel}
          className="mb-4"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          근태관리로 돌아가기
        </Button>

        <div className="flex items-center gap-3">
          <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center">
            <typeInfo.Icon className="w-6 h-6 text-primary" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">{typeInfo.label}</h1>
            <p className="text-muted-foreground">{typeInfo.description}</p>
          </div>
        </div>
      </div>

      {/* 폼 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileCheck className="w-5 h-5" />
            신청 정보
          </CardTitle>
          <CardDescription>
            필수 정보를 입력해주세요
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 제목 */}
          <div className="space-y-2">
            <Label htmlFor="title">제목</Label>
            <Input
              id="title"
              placeholder={`${typeInfo.label} 제목을 입력하세요`}
              value={formData.title}
              onChange={(e) => handleChange('title', e.target.value)}
            />
          </div>

          {/* 날짜 (출장/휴가/외근) */}
          {['businessTripRequest', 'vacationRequest', 'fieldWorkRequest'].includes(documentType) && (
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="startDate">시작일</Label>
                <Input
                  id="startDate"
                  type="date"
                  value={formData.startDate}
                  onChange={(e) => handleChange('startDate', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="endDate">종료일</Label>
                <Input
                  id="endDate"
                  type="date"
                  value={formData.endDate}
                  onChange={(e) => handleChange('endDate', e.target.value)}
                />
              </div>
            </div>
          )}

          {/* 시간 (연장근무) */}
          {documentType === 'overtimeRequest' && (
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="startTime">시작 시간</Label>
                <Input
                  id="startTime"
                  type="time"
                  value={formData.startTime}
                  onChange={(e) => handleChange('startTime', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="endTime">종료 시간</Label>
                <Input
                  id="endTime"
                  type="time"
                  value={formData.endTime}
                  onChange={(e) => handleChange('endTime', e.target.value)}
                />
              </div>
            </div>
          )}

          {/* 목적지/장소 (출장/외근) */}
          {['businessTripRequest', 'fieldWorkRequest'].includes(documentType) && (
            <div className="space-y-2">
              <Label htmlFor="destination">
                {documentType === 'businessTripRequest' ? '출장지' : '외근 장소'}
              </Label>
              <Input
                id="destination"
                placeholder="장소를 입력하세요"
                value={formData.destination}
                onChange={(e) => handleChange('destination', e.target.value)}
              />
            </div>
          )}

          {/* 목적/사유 */}
          <div className="space-y-2">
            <Label htmlFor="purpose">
              {documentType === 'vacationRequest' ? '휴가 사유' : '목적'}
            </Label>
            <Input
              id="purpose"
              placeholder={documentType === 'vacationRequest' ? '휴가 사유를 입력하세요' : '목적을 입력하세요'}
              value={formData.purpose}
              onChange={(e) => handleChange('purpose', e.target.value)}
            />
          </div>

          {/* 상세 내용 */}
          <div className="space-y-2">
            <Label htmlFor="content">상세 내용</Label>
            <Textarea
              id="content"
              placeholder="상세 내용을 입력하세요"
              rows={4}
              value={formData.content}
              onChange={(e) => handleChange('content', e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* 버튼 */}
      <div className="flex justify-end gap-3 mt-6">
        <Button variant="outline" onClick={handleCancel}>
          취소
        </Button>
        <Button onClick={handleSubmit} disabled={isSubmitting}>
          {isSubmitting ? '등록 중...' : '등록'}
        </Button>
      </div>
    </div>
  );
}

function DocumentListContent() {
  const router = useRouter();

  return (
    <div className="container mx-auto py-6">
      <div className="text-center py-12">
        <FileText className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
        <h2 className="text-xl font-semibold mb-2">HR 문서 관리</h2>
        <p className="text-muted-foreground mb-6">
          근태관리에서 사유 등록 시 문서를 작성할 수 있습니다.
        </p>
        <Button onClick={() => router.push('/hr/attendance')}>
          근태관리로 이동
        </Button>
      </div>
    </div>
  );
}

export default function DocumentsPage() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');

  if (mode === 'new') {
    return (
      <Suspense fallback={<FormSectionSkeleton fields={6} />}>
        <DocumentNewContent />
      </Suspense>
    );
  }

  return <DocumentListContent />;
}
