'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { DollarSign, ArrowLeft, Trash2, Edit, X, Save, Plus, List } 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 { Textarea } from '@/components/ui/textarea';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
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 { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import type { Pricing, PricingStatus } from './types';
import { PRICING_STATUS_LABELS } from './types';
import {
  getPricingDetail,
  createPricing,
  updatePricing,
  deletePricing,
  getVendorList,
} from './actions';

interface PricingDetailClientProps {
  id?: string;
  mode: 'view' | 'create' | 'edit';
}

interface FormData {
  itemType: string;
  category: string;
  itemName: string;
  spec: string;
  unit: string;
  division: string;
  vendor: string;
  sellingPrice: number;
  status: PricingStatus;
  note: string;
}

const initialFormData: FormData = {
  itemType: '',
  category: '',
  itemName: '',
  spec: '',
  unit: '',
  division: '',
  vendor: '',
  sellingPrice: 0,
  status: 'in_use',
  note: '',
};

export default function PricingDetailClient({ id, mode }: PricingDetailClientProps) {
  const router = useRouter();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const [pricing, setPricing] = useState<Pricing | null>(null);
  const [formData, setFormData] = useState<FormData>(initialFormData);
  const [vendors, setVendors] = useState<{ id: string; name: string }[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

  const isViewMode = mode === 'view';
  const isCreateMode = mode === 'create';
  const isEditMode = mode === 'edit';

  // 데이터 로드
  useEffect(() => {
    const loadData = async () => {
      setIsLoading(true);
      try {
        // 거래처 목록 로드
        const vendorResult = await getVendorList();
        if (vendorResult.success && vendorResult.data) {
          setVendors(vendorResult.data);
        }

        // 상세 데이터 로드 (수정/보기 모드)
        if (id && (isViewMode || isEditMode)) {
          const result = await getPricingDetail(id);
          if (result.success && result.data) {
            setPricing(result.data);
            setFormData({
              itemType: result.data.itemType,
              category: result.data.category,
              itemName: result.data.itemName,
              spec: result.data.spec,
              unit: result.data.unit,
              division: result.data.division,
              vendor: result.data.vendor,
              sellingPrice: result.data.sellingPrice,
              status: result.data.status,
              note: '',
            });
          } else {
            toast.error(result.error || '데이터를 불러올 수 없습니다.');
            router.push('/ko/construction/order/base-info/pricing');
          }
        }
      } catch {
        toast.error('데이터 로드에 실패했습니다.');
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [id, mode, isViewMode, isEditMode, router]);

  // 판매단가 변경
  const handleSellingPriceChange = useCallback((value: string) => {
    const numValue = parseFloat(value) || 0;
    setFormData((prev) => ({
      ...prev,
      sellingPrice: numValue,
    }));
  }, []);

  // 거래처 변경
  const handleVendorChange = useCallback((value: string) => {
    setFormData((prev) => ({ ...prev, vendor: value }));
  }, []);

  // 상태 변경
  const handleStatusChange = useCallback((value: string) => {
    setFormData((prev) => ({ ...prev, status: value as PricingStatus }));
  }, []);

  // 비고 변경
  const handleNoteChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setFormData((prev) => ({ ...prev, note: e.target.value }));
  }, []);

  // 저장
  const handleSave = useCallback(async () => {
    setIsLoading(true);
    try {
      if (isCreateMode) {
        const result = await createPricing({
          itemType: formData.itemType,
          category: formData.category,
          itemName: formData.itemName,
          spec: formData.spec,
          orderItems: [],
          unit: formData.unit,
          division: formData.division,
          vendor: formData.vendor,
          sellingPrice: formData.sellingPrice,
          status: formData.status,
        });

        if (result.success) {
          toast.success('단가가 등록되었습니다.');
          router.push('/ko/construction/order/base-info/pricing');
        } else {
          toast.error(result.error || '등록에 실패했습니다.');
        }
      } else if (isEditMode && id) {
        const result = await updatePricing(id, {
          vendor: formData.vendor,
          sellingPrice: formData.sellingPrice,
          status: formData.status,
        });

        if (result.success) {
          toast.success('단가가 수정되었습니다.');
          router.push(`/ko/construction/order/base-info/pricing/${id}?mode=view`);
        } else {
          toast.error(result.error || '수정에 실패했습니다.');
        }
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [isCreateMode, isEditMode, id, formData, router]);

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

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

  // 수정 페이지로 이동
  const handleEdit = useCallback(() => {
    if (id) {
      router.push(`/ko/construction/order/base-info/pricing/${id}?mode=edit`);
    }
  }, [id, router]);

  // 취소
  const handleCancel = useCallback(() => {
    if (isCreateMode) {
      router.push('/ko/construction/order/base-info/pricing');
    } else if (isEditMode && id) {
      router.push(`/ko/construction/order/base-info/pricing/${id}?mode=view`);
    }
  }, [isCreateMode, isEditMode, id, router]);

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

  // 숫자 포맷
  const formatNumber = (num: number) => num.toLocaleString('ko-KR');

  // 페이지 제목
  const pageTitle = isCreateMode ? '단가 등록' : isEditMode ? '단가 수정' : '단가 상세';
  const pageDescription = '단가 정보를 등록하고 관리합니다';

  // 동적 항목 (무게, 두께 등) 가져오기
  const dynamicOrderItems = pricing?.orderItems || [];

  return (
    <PageLayout>
      <PageHeader
        title={pageTitle}
        description={pageDescription}
        icon={DollarSign}
      />

      <div className="space-y-6 pb-24">
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 단가번호 / 품목유형 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>단가번호</Label>
              {isCreateMode ? (
                <Input value="자동생성" disabled />
              ) : (
                <Input value={pricing?.pricingNumber || ''} disabled />
              )}
            </div>
            <div className="space-y-2">
              <Label>품목유형</Label>
              <Input value={formData.itemType} disabled />
            </div>
          </div>

          {/* 카테고리명 / 품목명 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>카테고리명</Label>
              <Input value={formData.category} disabled />
            </div>
            <div className="space-y-2">
              <Label>품목명</Label>
              <Input value={formData.itemName} disabled />
            </div>
          </div>

          {/* 규격 / 동적항목 (무게 등) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>규격</Label>
              <Input value={formData.spec} disabled />
            </div>
            {dynamicOrderItems.length > 0 ? (
              <div className="space-y-2">
                <Label>{dynamicOrderItems[0]?.name || '무게'}</Label>
                <Input value={dynamicOrderItems[0]?.value || '-'} disabled />
              </div>
            ) : (
              <div className="space-y-2">
                <Label>무게</Label>
                <Input value="-" disabled />
              </div>
            )}
          </div>

          {/* 단위 / 구분 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>단위</Label>
              <Input value={formData.unit} disabled />
            </div>
            <div className="space-y-2">
              <Label>구분</Label>
              <Input value={formData.division} disabled />
            </div>
          </div>

          {/* 거래처 / 판매단가 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>거래처</Label>
              {isViewMode ? (
                <Input value={formData.vendor} disabled />
              ) : (
                <Select value={formData.vendor} onValueChange={handleVendorChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="거래처 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {vendors.map((vendor) => (
                      <SelectItem key={vendor.id} value={vendor.name}>
                        {vendor.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
            <div className="space-y-2">
              <Label>판매단가</Label>
              {isViewMode ? (
                <Input value={formatNumber(formData.sellingPrice)} disabled />
              ) : (
                <CurrencyInput
                  value={formData.sellingPrice}
                  onChange={(value) => handleSellingPriceChange(String(value ?? 0))}
                  placeholder="판매단가 입력"
                />
              )}
            </div>
          </div>

          {/* 상태 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>상태</Label>
              {isViewMode ? (
                <Input value={PRICING_STATUS_LABELS[formData.status]} disabled />
              ) : (
                <Select value={formData.status} onValueChange={handleStatusChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="상태 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="in_use">사용</SelectItem>
                    <SelectItem value="stopped">중지</SelectItem>
                  </SelectContent>
                </Select>
              )}
            </div>
            <div />
          </div>

          {/* 비고 */}
          <div className="space-y-2">
            <Label>비고</Label>
            {isViewMode ? (
              <Textarea value={formData.note || '-'} disabled rows={3} />
            ) : (
              <Textarea
                value={formData.note}
                onChange={handleNoteChange}
                placeholder="비고 입력"
                rows={3}
              />
            )}
          </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">
          {isViewMode && (
            <>
              <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={handleEdit}>
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
            </>
          )}
          {isEditMode && (
            <>
              <Button variant="outline" onClick={handleCancel}>
                <X className="h-4 w-4 mr-2" />
                취소
              </Button>
              <Button onClick={handleSave} disabled={isLoading}>
                <Save className="h-4 w-4 mr-2" />
                {isLoading ? '저장 중...' : '저장'}
              </Button>
            </>
          )}
          {isCreateMode && (
            <>
              <Button variant="outline" onClick={handleCancel}>
                <X className="h-4 w-4 mr-2" />
                취소
              </Button>
              <Button onClick={handleSave} disabled={isLoading}>
                <Plus className="h-4 w-4 mr-2" />
                {isLoading ? '등록 중...' : '등록'}
              </Button>
            </>
          )}
        </div>
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        description="이 단가를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
        loading={isLoading}
        onConfirm={handleDelete}
      />
    </PageLayout>
  );
}
