'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { FormField } from '@/components/molecules/FormField';
import { PageLayout, PageHeader } from '@/components/organisms';
import { DetailActions } from '@/components/templates/IntegratedDetailTemplate/components/DetailActions';
import { Gift, AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import {
  createGiftCertificate,
  updateGiftCertificate,
  deleteGiftCertificate,
} from './actions';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import {
  PURCHASE_PURPOSE_OPTIONS,
  ENTERTAINMENT_EXPENSE_OPTIONS,
  STATUS_OPTIONS,
  FACE_VALUE_THRESHOLD,
  createEmptyFormData,
} from './types';
import type { GiftCertificateFormData } from './types';

interface GiftCertificateDetailProps {
  mode: 'new' | 'edit' | 'view';
  initialData?: GiftCertificateFormData;
  id?: string;
}

export function GiftCertificateDetail({
  mode,
  initialData,
  id,
}: GiftCertificateDetailProps) {
  const router = useRouter();
  const [formData, setFormData] = useState<GiftCertificateFormData>(
    initialData ?? createEmptyFormData()
  );
  const [isSubmitting, setIsSubmitting] = useState(false);

  const isNew = mode === 'new';
  const isView = mode === 'view';
  const isEditable = !isView;
  const showUsageInfo = formData.faceValue >= FACE_VALUE_THRESHOLD;

  const handleChange = useCallback(
    (field: keyof GiftCertificateFormData, value: string | number) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
    },
    []
  );

  const handleSubmit = useCallback(async () => {
    if (!formData.name.trim()) {
      toast.error('상품권명을 입력하세요.');
      return;
    }
    if (!formData.faceValue || formData.faceValue <= 0) {
      toast.error('액면가를 입력하세요.');
      return;
    }
    if (!formData.purchaseDate) {
      toast.error('구입일을 선택하세요.');
      return;
    }

    // 50만원 이상 시 상품권 정보 필수 체크
    if (showUsageInfo && formData.status === 'used') {
      if (!formData.recipientName.trim()) {
        toast.error('수령인을 입력하세요.');
        return;
      }
    }

    setIsSubmitting(true);
    try {
      const result = isNew
        ? await createGiftCertificate(formData)
        : await updateGiftCertificate(id!, formData);

      if (result.success) {
        invalidateDashboard('giftCertificate');
        toast.success(isNew ? '상품권이 등록되었습니다.' : '상품권이 수정되었습니다.');
        router.push('/ko/accounting/gift-certificates');
      } else {
        toast.error(result.error || '처리에 실패했습니다.');
      }
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, isNew, id, showUsageInfo, router]);

  const handleDelete = useCallback(async () => {
    if (!id) return;
    setIsSubmitting(true);
    try {
      const result = await deleteGiftCertificate(id);
      if (result.success) {
        invalidateDashboard('giftCertificate');
        toast.success('상품권이 삭제되었습니다.');
        router.push('/ko/accounting/gift-certificates');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsSubmitting(false);
    }
  }, [id, router]);

  // 상태 옵션 (등록 시 '전체' 제외)
  const statusDetailOptions = STATUS_OPTIONS.filter((opt) => opt.value !== 'all');

  return (
    <PageLayout>
      <PageHeader
        title={isNew ? '상품권 등록' : isView ? '상품권 상세' : '상품권 수정'}
        description={
          isNew
            ? '새 상품권을 등록합니다.'
            : isView
              ? '상품권 상세 정보를 확인합니다.'
              : '상품권 정보를 수정합니다.'
        }
        icon={Gift}
      />

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="일련번호"
              value={formData.serialNumber}
              onChange={(v) => handleChange('serialNumber', v)}
              placeholder="일련번호를 입력하세요"
              disabled={!isEditable}
            />
            <FormField
              label="상품권명"
              required={isEditable}
              value={formData.name}
              onChange={(v) => handleChange('name', v)}
              placeholder="상품권명을 입력하세요"
              disabled={!isEditable}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="액면가"
              required={isEditable}
              type="currency"
              value={formData.faceValue}
              onChangeNumber={(v) => handleChange('faceValue', v ?? 0)}
              placeholder="0"
              disabled={!isEditable}
            />
            <FormField
              label="구입처"
              type="select"
              value={formData.vendorId}
              onChange={(v) => handleChange('vendorId', v)}
              options={[]}
              selectPlaceholder="거래처 선택"
              helpText="매입 거래처명 목록 (API 연동 후 사용 가능)"
              disabled={!isEditable}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="구입일"
              required={isEditable}
              type="date"
              value={formData.purchaseDate}
              onChange={(v) => handleChange('purchaseDate', v)}
              disabled={!isEditable}
            />
            <FormField
              label="구입목적"
              type="select"
              value={formData.purchasePurpose}
              onChange={(v) => handleChange('purchasePurpose', v)}
              options={PURCHASE_PURPOSE_OPTIONS}
              disabled={!isEditable}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="접대비"
              type="select"
              value={formData.entertainmentExpense}
              onChange={(v) => handleChange('entertainmentExpense', v)}
              options={ENTERTAINMENT_EXPENSE_OPTIONS}
              disabled={!isEditable}
            />
            <FormField
              label="상태"
              type="select"
              value={formData.status}
              onChange={(v) => handleChange('status', v)}
              options={statusDetailOptions}
              disabled={!isEditable}
            />
          </div>
        </CardContent>
      </Card>

      {/* 상품권 정보 (액면가 50만원 이상 시) */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            상품권 정보
            {showUsageInfo && <span className="text-red-500">*</span>}
          </CardTitle>
          {showUsageInfo ? (
            <p className="text-sm text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />
              액면가 50만원 이상일 경우 입력 필수입니다
            </p>
          ) : (
            <p className="text-sm text-muted-foreground">
              액면가 50만원 이상일 경우 입력이 필요합니다
            </p>
          )}
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="사용일"
              type="date"
              value={formData.usedDate}
              onChange={(v) => handleChange('usedDate', v)}
              disabled={!isEditable}
            />
            <FormField
              label="수령인"
              value={formData.recipientName}
              onChange={(v) => handleChange('recipientName', v)}
              placeholder="수령인 이름"
              required={showUsageInfo && isEditable}
              disabled={!isEditable}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <FormField
              label="수령인 소속"
              value={formData.recipientOrganization}
              onChange={(v) => handleChange('recipientOrganization', v)}
              placeholder="회사명"
              disabled={!isEditable}
            />
            <FormField
              label="사용처/용도"
              value={formData.usageDescription}
              onChange={(v) => handleChange('usageDescription', v)}
              placeholder="내용"
              disabled={!isEditable}
            />
          </div>

          <FormField
            label="비고"
            type="textarea"
            value={formData.memo}
            onChange={(v) => handleChange('memo', v)}
            placeholder="비고 사항을 입력하세요"
            rows={3}
            disabled={!isEditable}
          />
        </CardContent>
      </Card>

      {/* 하단 버튼 (DetailActions sticky 패턴) */}
      <DetailActions
        mode={isNew ? 'create' : isView ? 'view' : 'edit'}
        sticky
        isSubmitting={isSubmitting}
        onBack={() => router.push('/ko/accounting/gift-certificates')}
        onCancel={() => router.push('/ko/accounting/gift-certificates')}
        onEdit={() => router.push(`/ko/accounting/gift-certificates?mode=edit&id=${id}`)}
        onDelete={!isNew ? handleDelete : undefined}
        onSubmit={handleSubmit}
      />
    </PageLayout>
  );
}
