'use client';

/**
 * 재고현황 상세/수정 페이지
 *
 * 기획서 기준:
 * - 기본 정보: 자재번호, 품목코드, 품목유형, 품목명, 규격, 단위, 재고량 (읽기 전용)
 * - 수정 가능: 안전재고, 상태 (사용/미사용)
 * - 재고 조정: 이력 테이블 + 추가 기능
 */

import { useState, useCallback, useEffect } from 'react';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { useRouter, useSearchParams } from 'next/navigation';
import { Plus, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { stockStatusConfig } from './stockStatusConfig';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import {
  getStockById,
  updateStock,
  getStockAdjustments,
  createStockAdjustment,
} from './actions';
import type { StockAdjustmentRecord } from './actions';
import { USE_STATUS_LABELS, ITEM_TYPE_LABELS } from './types';
import type { ItemType } from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { toast } from 'sonner';

interface StockStatusDetailProps {
  id: string;
}

// 상세 페이지용 데이터 타입
interface StockDetailData {
  id: string;
  stockNumber: string;
  itemCode: string;
  itemType: ItemType;
  itemName: string;
  specification: string;
  unit: string;
  calculatedQty: number;
  safetyStock: number;
  maxStock: number;
  wipStatus: 'active' | 'inactive';
  useStatus: 'active' | 'inactive';
}

export function StockStatusDetail({ id }: StockStatusDetailProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const initialMode = searchParams.get('mode') === 'edit' ? 'edit' : 'view';

  // API 데이터 상태
  const [detail, setDetail] = useState<StockDetailData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 폼 데이터 (수정 모드용) - wipStatus는 읽기 전용이므로 제외
  const [formData, setFormData] = useState<{
    safetyStock: number;
    maxStock: number;
    useStatus: 'active' | 'inactive';
  }>({
    safetyStock: 0,
    maxStock: 0,
    useStatus: 'active',
  });

  // 저장 중 상태
  const [, setIsSaving] = useState(false);

  // 재고 조정 상태
  const [adjustments, setAdjustments] = useState<StockAdjustmentRecord[]>([]);
  const [isAdjustmentDialogOpen, setIsAdjustmentDialogOpen] = useState(false);
  const [adjustmentForm, setAdjustmentForm] = useState({ quantity: '', remark: '' });
  const [isAdjustmentSaving, setIsAdjustmentSaving] = useState(false);

  // API 데이터 로드
  const loadData = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const result = await getStockById(id);

      if (result.success && result.data) {
        const data = result.data;
        // API 응답을 상세 페이지용 데이터로 변환
        const detailData: StockDetailData = {
          id: data.id,
          stockNumber: data.id, // stockNumber가 없으면 id 사용
          itemCode: data.itemCode,
          itemType: (data.itemType || 'RM') as ItemType,
          itemName: data.itemName,
          specification: data.specification || '-',
          unit: data.unit,
          calculatedQty: data.currentStock, // 재고량
          safetyStock: data.safetyStock,
          maxStock: data.maxStock || 0,
          wipStatus: 'active', // 재공품 상태 (기본값: 사용)
          useStatus: data.status === null ? 'active' : 'active', // 기본값
        };
        setDetail(detailData);
        setFormData({
          safetyStock: detailData.safetyStock,
          maxStock: detailData.maxStock,
          useStatus: detailData.useStatus,
        });
      } else {
        setError(result.error || '재고 정보를 찾을 수 없습니다.');
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      console.error('[StockStatusDetail] loadData error:', err);
      setError('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  // 재고 조정 이력 로드
  const loadAdjustments = useCallback(async () => {
    try {
      const result = await getStockAdjustments(id);
      if (result.success && result.data) {
        setAdjustments(result.data);
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      console.error('[StockStatusDetail] loadAdjustments error:', err);
    }
  }, [id]);

  // 데이터 로드
  useEffect(() => {
    loadData();
    loadAdjustments();
  }, [loadData, loadAdjustments]);

  // 폼 값 변경 핸들러
  const handleInputChange = (field: keyof typeof formData, value: string | number) => {
    setFormData((prev) => ({
      ...prev,
      [field]: field === 'useStatus' ? value : Number(value),
    }));
  };

  // 저장 시 검증
  const validateForm = (): string | null => {
    if (formData.maxStock > 0 && formData.safetyStock > formData.maxStock) {
      return '최대재고는 안전재고 이상이어야 합니다.';
    }
    return null;
  };

  // 저장 핸들러
  const handleSave = async () => {
    if (!detail) return;

    const validationError = validateForm();
    if (validationError) {
      toast.error(validationError);
      return;
    }

    setIsSaving(true);
    try {
      const result = await updateStock(id, formData);

      if (result.success) {
        invalidateDashboard('stock');
        toast.success('재고 정보가 저장되었습니다.');
        // 상세 데이터 업데이트
        setDetail((prev) =>
          prev
            ? {
                ...prev,
                safetyStock: formData.safetyStock,
                maxStock: formData.maxStock,
                useStatus: formData.useStatus,
              }
            : null
        );
        // view 모드로 전환
        router.push(`/ko/material/stock-status/${id}?mode=view`);
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      console.error('[StockStatusDetail] handleSave error:', err);
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  };

  // 재고 조정 등록
  const handleAdjustmentSave = async () => {
    const qty = Number(adjustmentForm.quantity);
    if (!qty || qty === 0) {
      toast.error('증감 수량을 입력해주세요. (0 제외)');
      return;
    }

    setIsAdjustmentSaving(true);
    try {
      const result = await createStockAdjustment(id, {
        quantity: qty,
        remark: adjustmentForm.remark || undefined,
      });

      if (result.success) {
        toast.success('재고 조정이 등록되었습니다.');
        setIsAdjustmentDialogOpen(false);
        setAdjustmentForm({ quantity: '', remark: '' });
        // 이력 + 기본 정보 새로고침
        loadAdjustments();
        loadData();
      } else {
        toast.error(result.error || '재고 조정 등록에 실패했습니다.');
      }
    } catch (err) {
      if (isNextRedirectError(err)) throw err;
      toast.error('재고 조정 등록 중 오류가 발생했습니다.');
    } finally {
      setIsAdjustmentSaving(false);
    }
  };

  // 읽기 전용 필드 렌더링 (수정 모드에서 구분용)
  const renderReadOnlyField = (label: string, value: string | number, isEditMode = false) => (
    <div>
      <Label className="text-sm text-muted-foreground">{label}</Label>
      {isEditMode ? (
        // 수정 모드: 읽기 전용임을 명확히 표시 (어두운 배경 + cursor-not-allowed)
        <div className="mt-1.5 px-3 py-2 bg-gray-200 border border-gray-300 rounded-md text-sm text-gray-500 cursor-not-allowed select-none">
          {value}
        </div>
      ) : (
        // 보기 모드: 일반 텍스트 스타일
        <div className="mt-1.5 px-3 py-2 bg-gray-50 border rounded-md text-sm">
          {value}
        </div>
      )}
    </div>
  );

  // 재고 조정 섹션 (view/edit 공통)
  const renderAdjustmentSection = () => (
    <Card>
      <CardHeader className="pb-4 flex flex-row items-center justify-between">
        <CardTitle className="text-base font-medium">재고 조정</CardTitle>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => setIsAdjustmentDialogOpen(true)}
        >
          <Plus className="w-4 h-4 mr-1" />
          추가
        </Button>
      </CardHeader>
      <CardContent>
        <div className="border rounded-md overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-50">
                <TableHead className="text-center w-[50px]">No</TableHead>
                <TableHead className="text-center min-w-[140px]">조정일시</TableHead>
                <TableHead className="text-center min-w-[100px]">증감 수량</TableHead>
                <TableHead className="text-center min-w-[100px]">조정 후 재고</TableHead>
                <TableHead className="min-w-[150px]">사유</TableHead>
                <TableHead className="text-center min-w-[80px]">검수자</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {adjustments.length > 0 ? (
                adjustments.map((adj, idx) => (
                  <TableRow key={adj.id}>
                    <TableCell className="text-center">{idx + 1}</TableCell>
                    <TableCell className="text-center text-sm">{adj.adjusted_at}</TableCell>
                    <TableCell className={`text-center font-medium ${adj.quantity > 0 ? 'text-blue-600' : 'text-red-600'}`}>
                      {adj.quantity > 0 ? `+${adj.quantity}` : adj.quantity}
                    </TableCell>
                    <TableCell className="text-center">{adj.balance_qty}</TableCell>
                    <TableCell className="text-sm">{adj.remark || '-'}</TableCell>
                    <TableCell className="text-center">{adj.inspector}</TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-6 text-muted-foreground">
                    재고 조정 이력이 없습니다.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );

  // 상세 보기 모드 렌더링
  const renderViewContent = useCallback(() => {
    if (!detail) return null;

    return (
      <div className="space-y-6">
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-base font-medium">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* Row 1: 자재번호, 품목코드, 품목유형, 품목명 */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {renderReadOnlyField('자재번호', detail.stockNumber)}
                {renderReadOnlyField('품목코드', detail.itemCode)}
                {renderReadOnlyField('품목유형', ITEM_TYPE_LABELS[detail.itemType] || '-')}
                {renderReadOnlyField('품목명', detail.itemName)}
              </div>

              {/* Row 2: 규격, 단위, 재고량, 안전재고(최소) */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {renderReadOnlyField('규격', detail.specification)}
                {renderReadOnlyField('단위', detail.unit)}
                {renderReadOnlyField('재고량', detail.calculatedQty)}
                {renderReadOnlyField('안전재고 (최소)', detail.safetyStock)}
              </div>

              {/* Row 3: 최대재고, 재공품, 상태 */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {renderReadOnlyField('최대재고', detail.maxStock > 0 ? detail.maxStock : '-')}
                {renderReadOnlyField('재공품', USE_STATUS_LABELS[detail.wipStatus])}
                {renderReadOnlyField('상태', USE_STATUS_LABELS[detail.useStatus])}
              </div>
            </div>
          </CardContent>
        </Card>

        {renderAdjustmentSection()}
      </div>
    );
  }, [detail, adjustments]);

  // 수정 모드 렌더링
  const renderFormContent = useCallback(() => {
    if (!detail) return null;

    return (
      <div className="space-y-6">
        <Card>
          <CardHeader className="pb-4">
            <CardTitle className="text-base font-medium">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* Row 1: 자재번호, 품목코드, 품목유형, 품목명 (읽기 전용) */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {renderReadOnlyField('자재번호', detail.stockNumber, true)}
                {renderReadOnlyField('품목코드', detail.itemCode, true)}
                {renderReadOnlyField('품목유형', ITEM_TYPE_LABELS[detail.itemType] || '-', true)}
                {renderReadOnlyField('품목명', detail.itemName, true)}
              </div>

              {/* Row 2: 규격, 단위, 재고량 (읽기 전용) + 안전재고 (수정 가능) */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {renderReadOnlyField('규격', detail.specification, true)}
                {renderReadOnlyField('단위', detail.unit, true)}
                {renderReadOnlyField('재고량', detail.calculatedQty, true)}

                {/* 안전재고 (수정 가능) */}
                <div>
                  <Label htmlFor="safetyStock" className="text-sm text-muted-foreground">
                    안전재고 (최소)
                  </Label>
                  <Input
                    id="safetyStock"
                    type="number"
                    value={formData.safetyStock}
                    onChange={(e) => handleInputChange('safetyStock', e.target.value)}
                    className="mt-1.5 border-gray-300 focus:border-blue-500 focus:ring-blue-500"
                    min={0}
                  />
                </div>
              </div>

              {/* Row 3: 최대재고 (수정 가능), 재공품 (읽기 전용), 상태 (수정 가능) */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {/* 최대재고 (수정 가능) */}
                <div>
                  <Label htmlFor="maxStock" className="text-sm text-muted-foreground">
                    최대재고
                  </Label>
                  <Input
                    id="maxStock"
                    type="number"
                    value={formData.maxStock}
                    onChange={(e) => handleInputChange('maxStock', e.target.value)}
                    className="mt-1.5 border-gray-300 focus:border-blue-500 focus:ring-blue-500"
                    min={0}
                    placeholder="0 = 미설정"
                  />
                </div>
                {/* 재공품 (읽기 전용) */}
                {renderReadOnlyField('재공품', USE_STATUS_LABELS[detail.wipStatus], true)}
                {/* 상태 (수정 가능) */}
                <div>
                  <Label htmlFor="useStatus" className="text-sm text-muted-foreground">
                    상태
                  </Label>
                  <Select
                    key={`useStatus-${formData.useStatus}`}
                    value={formData.useStatus}
                    onValueChange={(value) => handleInputChange('useStatus', value)}
                  >
                    <SelectTrigger className="mt-1.5 border-gray-300 focus:border-blue-500 focus:ring-blue-500">
                      <SelectValue placeholder="상태 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">사용</SelectItem>
                      <SelectItem value="inactive">미사용</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {renderAdjustmentSection()}
      </div>
    );
  }, [detail, formData, adjustments]);

  // 에러 상태 표시
  if (!isLoading && (error || !detail)) {
    return (
      <ServerErrorPage
        title="재고 정보를 불러올 수 없습니다"
        message={error || '재고 정보를 찾을 수 없습니다.'}
        onRetry={loadData}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <>
      <IntegratedDetailTemplate
        config={stockStatusConfig}
        mode={initialMode as 'view' | 'edit'}
        initialData={(detail || undefined) as Record<string, unknown> | undefined}
        itemId={id}
        isLoading={isLoading}
        renderView={() => renderViewContent()}
        renderForm={() => renderFormContent()}
        onSubmit={async () => { await handleSave(); return { success: true }; }}
      />

      {/* 재고 조정 등록 다이얼로그 */}
      <Dialog open={isAdjustmentDialogOpen} onOpenChange={setIsAdjustmentDialogOpen}>
        <DialogContent className="max-w-[400px]">
          <DialogHeader>
            <DialogTitle>재고 조정</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 pt-2">
            <div>
              <Label className="text-sm">
                증감 수량 <span className="text-red-500">*</span>
              </Label>
              <Input
                type="number"
                value={adjustmentForm.quantity}
                onChange={(e) => setAdjustmentForm((prev) => ({ ...prev, quantity: e.target.value }))}
                placeholder="양수: 증가, 음수: 감소"
                className="mt-1.5"
              />
            </div>
            <div>
              <Label className="text-sm">사유</Label>
              <Textarea
                value={adjustmentForm.remark}
                onChange={(e) => setAdjustmentForm((prev) => ({ ...prev, remark: e.target.value }))}
                placeholder="조정 사유를 입력하세요 (선택)"
                className="mt-1.5"
                rows={3}
              />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button
                variant="outline"
                onClick={() => {
                  setIsAdjustmentDialogOpen(false);
                  setAdjustmentForm({ quantity: '', remark: '' });
                }}
                disabled={isAdjustmentSaving}
              >
                취소
              </Button>
              <Button
                onClick={handleAdjustmentSave}
                disabled={isAdjustmentSaving}
                className="bg-gray-900 text-white hover:bg-gray-800"
              >
                {isAdjustmentSaving && <Loader2 className="w-4 h-4 mr-1 animate-spin" />}
                저장
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
