'use client';

import { useState, useEffect } from 'react';
import { getTodayString } from '@/lib/utils/date';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { toast } from 'sonner';
import type { ProjectDetail, ProjectEndFormData } from './types';
import { PROJECT_END_STATUS_OPTIONS } from './types';
import { updateProjectEnd } from './actions';

interface ProjectEndDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  project: ProjectDetail | null;
  onSuccess?: () => void;
}

export default function ProjectEndDialog({
  open,
  onOpenChange,
  project,
  onSuccess,
}: ProjectEndDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState<ProjectEndFormData>({
    projectId: '',
    projectName: '',
    workDate: '',
    completionDate: '',
    status: 'in_progress',
    memo: '',
  });

  // 프로젝트가 변경되면 폼 데이터 초기화
  useEffect(() => {
    if (project) {
      setFormData({
        projectId: project.id,
        projectName: project.siteName,
        workDate: project.endDate, // 결선작업일은 프로젝트 종료일로 설정
        completionDate: getTodayString(), // 오늘 날짜
        status: project.status === 'completed' ? 'completed' : 'in_progress',
        memo: '',
      });
    }
  }, [project]);

  // 수정 버튼 클릭
  const handleSubmit = async () => {
    if (!project) return;

    setIsSubmitting(true);
    try {
      const result = await updateProjectEnd(formData);

      if (result.success) {
        toast.success('프로젝트 종료 처리가 완료되었습니다.');
        onOpenChange(false);
        onSuccess?.();
      } else {
        toast.error(result.error || '처리 중 오류가 발생했습니다.');
      }
    } catch {
      toast.error('처리 중 오류가 발생했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 삭제 버튼 클릭
  const handleDelete = () => {
    toast.info('삭제 기능은 준비 중입니다.');
  };

  if (!project) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>프로젝트 종료</DialogTitle>
        </DialogHeader>

        <div className="grid gap-4 py-4">
          {/* 프로젝트 (현장명) - 읽기전용 */}
          <div className="grid gap-2">
            <Label htmlFor="projectName">프로젝트</Label>
            <Input
              id="projectName"
              value={formData.projectName}
              disabled
              className="bg-muted"
            />
          </div>

          {/* 결선작업일 - 읽기전용 */}
          <div className="grid gap-2">
            <Label htmlFor="workDate">결선작업일</Label>
            <DatePicker
              value={formData.workDate}
              disabled
              className="bg-muted"
            />
          </div>

          {/* 결선완료일 - 입력 */}
          <div className="grid gap-2">
            <Label htmlFor="completionDate">결선완료일</Label>
            <DatePicker
              value={formData.completionDate}
              onChange={(date) =>
                setFormData((prev) => ({ ...prev, completionDate: date }))
              }
            />
          </div>

          {/* 상태 - 셀렉트 */}
          <div className="grid gap-2">
            <Label htmlFor="status">상태</Label>
            <Select
              value={formData.status}
              onValueChange={(value: 'in_progress' | 'completed') =>
                setFormData((prev) => ({ ...prev, status: value }))
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="상태 선택" />
              </SelectTrigger>
              <SelectContent>
                {PROJECT_END_STATUS_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 메모 - 텍스트에어리어 */}
          <div className="grid gap-2">
            <Label htmlFor="memo">메모</Label>
            <Textarea
              id="memo"
              placeholder="메모를 입력해주세요."
              value={formData.memo}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, memo: e.target.value }))
              }
              className="min-h-[100px]"
            />
          </div>
        </div>

        {/* 버튼 영역 */}
        <div className="flex justify-center gap-3">
          <Button
            variant="outline"
            onClick={handleDelete}
            disabled={isSubmitting}
            className="w-24"
          >
            삭제
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={isSubmitting}
            className="w-24"
          >
            {isSubmitting ? '처리중...' : '수정'}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}