'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Hammer, ArrowLeft, Trash2, Edit, X, Save, Plus } from 'lucide-react';
import { useMenuStore } from '@/store/menuStore';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { toast } from 'sonner';
import type { Labor, LaborFormData, LaborCategory, LaborStatus } from './types';
import { CATEGORY_OPTIONS, STATUS_OPTIONS } from './constants';
import { getLabor, createLabor, updateLabor, deleteLabor } from './actions';

interface LaborDetailClientProps {
  laborId?: string;
  isEditMode?: boolean;
  isNewMode?: boolean;
}

const initialFormData: LaborFormData = {
  laborNumber: '',
  category: '가로',
  minM: 0,
  maxM: 0,
  laborPrice: null,
  status: '사용',
};

export default function LaborDetailClient({
  laborId,
  isEditMode = false,
  isNewMode = false,
}: LaborDetailClientProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  // 모드 상태
  const [mode, setMode] = useState<'view' | 'edit' | 'new'>(
    isNewMode ? 'new' : isEditMode ? 'edit' : 'view'
  );

  // 폼 데이터
  const [formData, setFormData] = useState<LaborFormData>(initialFormData);
  const [originalData, setOriginalData] = useState<Labor | null>(null);

  // 소수점 입력을 위한 문자열 상태 (입력 중인 값 유지)
  const [minMInput, setMinMInput] = useState<string>('');
  const [maxMInput, setMaxMInput] = useState<string>('');

  // 상태
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

  // 노임 데이터 로드
  useEffect(() => {
    if (laborId && !isNewMode) {
      const loadLabor = async () => {
        setIsLoading(true);
        try {
          const result = await getLabor(laborId);
          if (result.success && result.data) {
            setOriginalData(result.data);
            setFormData({
              laborNumber: result.data.laborNumber,
              category: result.data.category,
              minM: result.data.minM,
              maxM: result.data.maxM,
              laborPrice: result.data.laborPrice,
              status: result.data.status,
            });
            // 소수점 입력용 문자열 상태 초기화
            setMinMInput(result.data.minM === 0 ? '' : result.data.minM.toString());
            setMaxMInput(result.data.maxM === 0 ? '' : result.data.maxM.toString());
          } else {
            toast.error(result.error || '노임 정보를 불러오는데 실패했습니다.');
            router.push('/ko/construction/order/base-info/labor');
          }
        } catch {
          toast.error('노임 정보를 불러오는데 실패했습니다.');
          router.push('/ko/construction/order/base-info/labor');
        } finally {
          setIsLoading(false);
        }
      };
      loadLabor();
    }
  }, [laborId, isNewMode, router]);

  // 폼 필드 변경
  const handleFieldChange = useCallback(
    (field: keyof LaborFormData, value: string | number | null) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
    },
    []
  );

  // 최소 M / 최대 M 입력 핸들러 (소수점 둘째자리까지)
  const handleMinMChange = useCallback(
    (value: string) => {
      // 빈 값 허용
      if (value === '') {
        setMinMInput('');
        handleFieldChange('minM', 0);
        return;
      }
      // 소수점 둘째자리까지 허용하는 정규식
      const regex = /^\d*\.?\d{0,2}$/;
      if (regex.test(value)) {
        setMinMInput(value);
        const numValue = parseFloat(value);
        if (!isNaN(numValue)) {
          handleFieldChange('minM', numValue);
        }
      }
    },
    [handleFieldChange]
  );

  const handleMaxMChange = useCallback(
    (value: string) => {
      // 빈 값 허용
      if (value === '') {
        setMaxMInput('');
        handleFieldChange('maxM', 0);
        return;
      }
      // 소수점 둘째자리까지 허용하는 정규식
      const regex = /^\d*\.?\d{0,2}$/;
      if (regex.test(value)) {
        setMaxMInput(value);
        const numValue = parseFloat(value);
        if (!isNaN(numValue)) {
          handleFieldChange('maxM', numValue);
        }
      }
    },
    [handleFieldChange]
  );

  // 노임단가 입력 핸들러 (정수만)
  const handleLaborPriceChange = useCallback(
    (value: string) => {
      if (value === '') {
        handleFieldChange('laborPrice', null);
        return;
      }
      // 정수만 허용
      const regex = /^\d*$/;
      if (regex.test(value)) {
        const numValue = parseInt(value, 10);
        if (!isNaN(numValue)) {
          handleFieldChange('laborPrice', numValue);
        }
      }
    },
    [handleFieldChange]
  );

  // 저장
  const handleSave = useCallback(async () => {
    // 유효성 검사
    if (!formData.laborNumber.trim()) {
      toast.error('노임번호를 입력해주세요.');
      return;
    }

    setIsSaving(true);
    try {
      if (mode === 'new') {
        const result = await createLabor(formData);
        if (result.success && result.data) {
          toast.success('노임이 등록되었습니다.');
          router.push(`/ko/construction/order/base-info/labor/${result.data.id}?mode=view`);
        } else {
          toast.error(result.error || '노임 등록에 실패했습니다.');
        }
      } else if (mode === 'edit' && laborId) {
        const result = await updateLabor(laborId, formData);
        if (result.success) {
          toast.success('노임이 수정되었습니다.');
          setMode('view');
          // 데이터 다시 로드
          const reloadResult = await getLabor(laborId);
          if (reloadResult.success && reloadResult.data) {
            setOriginalData(reloadResult.data);
          }
        } else {
          toast.error(result.error || '노임 수정에 실패했습니다.');
        }
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  }, [mode, formData, laborId, router]);

  // 삭제
  const handleDelete = useCallback(async () => {
    if (!laborId) return;

    setIsLoading(true);
    try {
      const result = await deleteLabor(laborId);
      if (result.success) {
        toast.success('노임이 삭제되었습니다.');
        router.push('/ko/construction/order/base-info/labor');
      } else {
        toast.error(result.error || '노임 삭제에 실패했습니다.');
      }
    } catch {
      toast.error('삭제 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
      setDeleteDialogOpen(false);
    }
  }, [laborId, router]);

  // 수정 모드 전환
  const handleEditMode = useCallback(() => {
    setMode('edit');
    router.replace(`/ko/construction/order/base-info/labor/${laborId}?mode=edit`);
  }, [laborId, router]);

  // 목록으로 이동
  const handleBack = useCallback(() => {
    router.push('/ko/construction/order/base-info/labor');
  }, [router]);

  // 취소
  const handleCancel = useCallback(() => {
    if (mode === 'new') {
      router.push('/ko/construction/order/base-info/labor');
    } else {
      setMode('view');
      // 원본 데이터로 복원
      if (originalData) {
        setFormData({
          laborNumber: originalData.laborNumber,
          category: originalData.category,
          minM: originalData.minM,
          maxM: originalData.maxM,
          laborPrice: originalData.laborPrice,
          status: originalData.status,
        });
        // 소수점 입력용 문자열 상태도 복원
        setMinMInput(originalData.minM === 0 ? '' : originalData.minM.toString());
        setMaxMInput(originalData.maxM === 0 ? '' : originalData.maxM.toString());
      }
      router.replace(`/ko/construction/order/base-info/labor/${laborId}`);
    }
  }, [mode, laborId, originalData, router]);

  // 읽기 전용 여부
  const isReadOnly = mode === 'view';

  // 페이지 타이틀
  const pageTitle = mode === 'new' ? '노임 등록' : '노임 상세';

  if (isLoading && !isNewMode) {
    return (
      <PageLayout>
        <PageHeader
          title={pageTitle}
          description="노임 정보를 등록하고 관리합니다."
          icon={Hammer}
        />
        <div className="flex items-center justify-center py-12">
          <div className="text-muted-foreground">로딩 중...</div>
        </div>
      </PageLayout>
    );
  }

  return (
    <>
      <PageLayout>
        <PageHeader
          title={pageTitle}
          description="노임 정보를 등록하고 관리합니다."
          icon={Hammer}
        />
        <div className="space-y-6 pb-24">
          {/* 기본 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">
                기본 정보 <span className="text-destructive">*</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Row 1: 노임번호, 구분 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="laborNumber">노임번호</Label>
                  <Input
                    id="laborNumber"
                    value={formData.laborNumber}
                    onChange={(e) => handleFieldChange('laborNumber', e.target.value)}
                    placeholder="노임번호를 입력하세요"
                    disabled={isReadOnly}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="category">구분</Label>
                  <Select
                    value={formData.category}
                    onValueChange={(v) => handleFieldChange('category', v as LaborCategory)}
                    disabled={isReadOnly}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="구분 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {CATEGORY_OPTIONS.filter((o) => o.value !== 'all').map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* Row 2: 최소 M, 최대 M */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="minM">최소 M</Label>
                  <Input
                    id="minM"
                    type="text"
                    inputMode="decimal"
                    value={minMInput}
                    onChange={(e) => handleMinMChange(e.target.value)}
                    placeholder="0.00"
                    disabled={isReadOnly}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="maxM">최대 M</Label>
                  <Input
                    id="maxM"
                    type="text"
                    inputMode="decimal"
                    value={maxMInput}
                    onChange={(e) => handleMaxMChange(e.target.value)}
                    placeholder="0.00"
                    disabled={isReadOnly}
                  />
                </div>
              </div>

              {/* Row 3: 노임단가, 상태 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="laborPrice">노임단가</Label>
                  <Input
                    id="laborPrice"
                    type="text"
                    inputMode="numeric"
                    value={formData.laborPrice === null ? '' : formData.laborPrice.toString()}
                    onChange={(e) => handleLaborPriceChange(e.target.value)}
                    placeholder="0"
                    disabled={isReadOnly}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="status">상태</Label>
                  <Select
                    value={formData.status}
                    onValueChange={(v) => handleFieldChange('status', v as LaborStatus)}
                    disabled={isReadOnly}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="상태 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {STATUS_OPTIONS.filter((o) => o.value !== 'all').map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 하단 액션 버튼 (sticky) */}
        <div className={`fixed bottom-6 ${sidebarCollapsed ? 'left-[156px]' : 'left-[316px]'} right-[48px] px-6 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 flex items-center justify-between`}>
          <Button variant="outline" onClick={handleBack}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
          <div className="flex items-center gap-2">
            {mode === 'view' && (
              <>
                <Button
                  variant="outline"
                  onClick={() => setDeleteDialogOpen(true)}
                  className="text-destructive hover:bg-destructive hover:text-destructive-foreground"
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
                <Button onClick={handleEditMode}>
                  <Edit className="h-4 w-4 mr-2" />
                  수정
                </Button>
              </>
            )}
            {mode === 'edit' && (
              <>
                <Button variant="outline" onClick={handleCancel}>
                  <X className="h-4 w-4 mr-2" />
                  취소
                </Button>
                <Button onClick={handleSave} disabled={isSaving}>
                  <Save className="h-4 w-4 mr-2" />
                  {isSaving ? '저장 중...' : '저장'}
                </Button>
              </>
            )}
            {mode === 'new' && (
              <>
                <Button variant="outline" onClick={handleCancel}>
                  <X className="h-4 w-4 mr-2" />
                  취소
                </Button>
                <Button onClick={handleSave} disabled={isSaving}>
                  <Plus className="h-4 w-4 mr-2" />
                  {isSaving ? '등록 중...' : '등록'}
                </Button>
              </>
            )}
          </div>
        </div>
      </PageLayout>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        description="이 노임을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다."
        loading={isLoading}
        onConfirm={handleDelete}
      />
    </>
  );
}