'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { NumberInput } from '@/components/ui/number-input';
import { DatePicker } from '@/components/ui/date-picker';
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Package, ClipboardList, MessageSquare, Tag, Layers, Search, X, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { FormSection } from '@/components/organisms/FormSection';
import {
  getBendingCodeMap,
  resolveBendingItem,
  generateBendingLot,
  createBendingStockOrder,
  updateBendingStockOrder,
  getMaterialLots,
  type BendingCodeMap,
  type BendingResolvedItem,
  type MaterialLot,
  type StockOrder,
} from './actions';
import type { DetailConfig } from '@/components/templates/IntegratedDetailTemplate/types';

// ============================================================================
// Config
// ============================================================================

const bendingCreateConfig: DetailConfig = {
  title: '절곡품 재고생산',
  description: '절곡품 재고생산을 등록합니다',
  icon: Package,
  basePath: '/sales/stocks',
  fields: [],
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '취소',
  },
};

const bendingEditConfig: DetailConfig = {
  title: '절곡품 재고생산',
  description: '절곡품 재고생산 정보를 수정합니다',
  icon: Package,
  basePath: '/sales/stocks',
  fields: [],
  actions: {
    showBack: true,
    showSave: true,
    submitLabel: '저장',
    backLabel: '취소',
  },
};

// ============================================================================
// LOT 프리뷰 날짜코드 생성
// ============================================================================

function generateDateCode(dateStr: string): string {
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '';
  const year = date.getFullYear() % 10;
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const monthCode =
    month >= 10 ? String.fromCharCode(55 + month) : String(month);
  return `${year}${monthCode}${String(day).padStart(2, '0')}`;
}

// ============================================================================
// 폼 상태
// ============================================================================

interface BendingFormState {
  regDate: string;
  prodCode: string;
  specCode: string;
  lengthCode: string;
  quantity: number;
  rawLotNo: string;
  fabricLotNo: string;
  memo: string;
}

function getInitialForm(): BendingFormState {
  const today = new Date();
  const yyyy = today.getFullYear();
  const mm = String(today.getMonth() + 1).padStart(2, '0');
  const dd = String(today.getDate()).padStart(2, '0');
  return {
    regDate: `${yyyy}-${mm}-${dd}`,
    prodCode: '',
    specCode: '',
    lengthCode: '',
    quantity: 1,
    rawLotNo: '',
    fabricLotNo: '',
    memo: '',
  };
}

// ============================================================================
// 원자재 LOT 선택 모달
// ============================================================================

function MaterialLotModal({
  open,
  onOpenChange,
  material,
  title,
  onSelect,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  material: string;
  title: string;
  onSelect: (lotNo: string) => void;
}) {
  const [lots, setLots] = useState<MaterialLot[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!open || !material) return;
    setIsLoading(true);
    getMaterialLots(material)
      .then((result) => {
        if (result.__authError) {
          toast.error('인증이 만료되었습니다.');
          return;
        }
        if (result.success && result.data) {
          setLots(result.data);
        } else {
          toast.error(result.error || 'LOT 목록 조회에 실패했습니다.');
        }
      })
      .finally(() => setIsLoading(false));
  }, [open, material]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <p className="text-sm text-muted-foreground">
          재질: <span className="font-medium">{material}</span>
        </p>
        <div className="flex-1 overflow-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : lots.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              해당 재질의 입고 LOT가 없습니다.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>LOT번호</TableHead>
                  <TableHead>품목명</TableHead>
                  <TableHead>규격</TableHead>
                  <TableHead className="text-right">입고수량</TableHead>
                  <TableHead>입고일</TableHead>
                  <TableHead>공급업체</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {lots.map((lot) => (
                  <TableRow
                    key={lot.id}
                    className="cursor-pointer hover:bg-accent"
                    onClick={() => {
                      onSelect(lot.lot_no);
                      onOpenChange(false);
                    }}
                  >
                    <TableCell>
                      <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                        {lot.lot_no}
                      </code>
                    </TableCell>
                    <TableCell>{lot.item_name}</TableCell>
                    <TableCell className="text-muted-foreground">{lot.specification}</TableCell>
                    <TableCell className="text-right">{lot.receiving_qty}</TableCell>
                    <TableCell>{lot.receiving_date}</TableCell>
                    <TableCell>{lot.supplier}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ============================================================================
// Component
// ============================================================================

interface BendingLotFormProps {
  initialData?: StockOrder;
  isEditMode?: boolean;
}

export function BendingLotForm({ initialData, isEditMode = false }: BendingLotFormProps) {
  const router = useRouter();
  const params = useParams();
  const locale = (params.locale as string) || 'ko';
  const basePath = `/${locale}/sales/stocks`;

  const isCopyMode = !isEditMode && !!initialData;

  const [form, setForm] = useState<BendingFormState>(() => {
    if (initialData?.bendingLot) {
      const bl = initialData.bendingLot;
      return {
        regDate: isCopyMode ? getInitialForm().regDate : (initialData.regDate || getInitialForm().regDate),
        prodCode: bl.prodCode || '',
        specCode: bl.specCode || '',
        lengthCode: bl.lengthCode || '',
        quantity: initialData.targetStockQty || initialData.quantity || 1,
        rawLotNo: bl.rawLotNo || '',
        fabricLotNo: bl.fabricLotNo || '',
        memo: initialData.memo || '',
      };
    }
    return getInitialForm();
  });
  const [codeMap, setCodeMap] = useState<BendingCodeMap | null>(null);
  const [resolvedItem, setResolvedItem] = useState<BendingResolvedItem | null>(null);
  const [resolveError, setResolveError] = useState<string>('');
  const [expectedItemCode, setExpectedItemCode] = useState<string>(
    initialData?.items?.[0]?.itemCode || ''
  );
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [rawLotModalOpen, setRawLotModalOpen] = useState(false);
  const [fabricLotModalOpen, setFabricLotModalOpen] = useState(false);

  const config = isEditMode
    ? bendingEditConfig
    : isCopyMode
      ? { ...bendingCreateConfig, description: '기존 재고생산을 복사하여 등록합니다' }
      : bendingCreateConfig;

  // 코드맵 로드 + edit mode 시 초기 품목 매핑 조회
  useEffect(() => {
    async function loadCodeMap() {
      const result = await getBendingCodeMap();
      if (result.__authError) {
        toast.error('인증이 만료되었습니다.');
        return;
      }
      if (result.success && result.data) {
        setCodeMap(result.data);

        // edit mode: 초기 데이터의 품목 매핑 자동 조회
        if (initialData?.bendingLot) {
          const bl = initialData.bendingLot;
          if (bl.prodCode && bl.specCode && bl.lengthCode) {
            const itemResult = await resolveBendingItem(bl.prodCode, bl.specCode, bl.lengthCode);
            if (itemResult.success && itemResult.data) {
              setResolvedItem(itemResult.data);
              if (itemResult.data.item_code) {
                setExpectedItemCode(itemResult.data.item_code);
              }
            } else if (itemResult.data?.expected_code) {
              setExpectedItemCode(itemResult.data.expected_code);
            }
          }
        }
      } else {
        toast.error(result.error || '코드맵 로딩에 실패했습니다.');
      }
      setIsLoading(false);
    }
    loadCodeMap();
  }, []);

  // 필터링된 종류 목록
  const filteredSpecs = useMemo(() => {
    if (!codeMap || !form.prodCode) return [];
    return codeMap.specs.filter((s) => s.products.includes(form.prodCode));
  }, [codeMap, form.prodCode]);

  // 필터링된 길이 목록
  const filteredLengths = useMemo(() => {
    if (!codeMap || !form.prodCode) return [];
    return form.prodCode === 'G'
      ? codeMap.lengths.smoke_barrier
      : codeMap.lengths.general;
  }, [codeMap, form.prodCode]);

  // 재질
  const material = useMemo(() => {
    if (!codeMap || !form.prodCode || !form.specCode) return '';
    return codeMap.material_map[`${form.prodCode}:${form.specCode}`] || '';
  }, [codeMap, form.prodCode, form.specCode]);

  // LOT 프리뷰
  const lotPreview = useMemo(() => {
    if (!form.prodCode || !form.specCode || !form.regDate) return '';
    const dateCode = generateDateCode(form.regDate);
    if (!dateCode) return '';
    const base = `${form.prodCode}${form.specCode}${dateCode}`;
    return form.lengthCode ? `${base}-${form.lengthCode}` : base;
  }, [form.prodCode, form.specCode, form.lengthCode, form.regDate]);

  // 연기차단재 여부
  const isSmokeBarrier = form.prodCode === 'G';

  // 품목명 변경
  const handleProdChange = useCallback((value: string) => {
    setForm((prev) => ({
      ...prev,
      prodCode: value,
      specCode: '',
      lengthCode: '',
    }));
    setResolvedItem(null);
    setResolveError('');
    setExpectedItemCode('');
  }, []);

  // 종류 변경
  const handleSpecChange = useCallback((value: string) => {
    setForm((prev) => ({
      ...prev,
      specCode: value,
      lengthCode: '',
    }));
    setResolvedItem(null);
    setResolveError('');
    setExpectedItemCode('');
  }, []);

  // 모양&길이 변경 → 품목 매핑 조회
  const handleLengthChange = useCallback(
    async (value: string) => {
      setForm((prev) => ({ ...prev, lengthCode: value }));
      setResolvedItem(null);
      setResolveError('');
      setExpectedItemCode('');

      if (form.prodCode && form.specCode && value) {
        const result = await resolveBendingItem(form.prodCode, form.specCode, value);
        if (result.__authError) {
          toast.error('인증이 만료되었습니다.');
          return;
        }
        if (result.success && result.data) {
          setResolvedItem(result.data);
          if (result.data.item_code) {
            setExpectedItemCode(result.data.item_code);
          }
        } else {
          const code = result.data?.expected_code;
          if (code) setExpectedItemCode(code);
          setResolveError(`해당 조합에 매핑된 품목이 없습니다.${code ? ` (${code})` : ''}`);
        }
      }
    },
    [form.prodCode, form.specCode]
  );

  // 저장
  const handleSave = useCallback(async (): Promise<{ success: boolean; error: string }> => {
    if (!form.prodCode) {
      toast.error('품목명을 선택하세요.');
      return { success: false, error: '' };
    }
    if (!form.specCode) {
      toast.error('종류를 선택하세요.');
      return { success: false, error: '' };
    }
    if (!form.lengthCode) {
      toast.error('모양&길이를 선택하세요.');
      return { success: false, error: '' };
    }
    if (form.quantity < 1) {
      toast.error('수량을 입력하세요.');
      return { success: false, error: '' };
    }

    setIsSaving(true);
    try {
      // 1. LOT 번호 생성
      const lotResult = await generateBendingLot(
        form.prodCode,
        form.specCode,
        form.lengthCode,
        form.regDate
      );
      if (lotResult.__authError) {
        toast.error('인증이 만료되었습니다.');
        return { success: false, error: '' };
      }
      if (!lotResult.success || !lotResult.data) {
        toast.error(lotResult.error || 'LOT 번호 생성에 실패했습니다.');
        return { success: false, error: '' };
      }

      const lotData = lotResult.data;

      // 2. 재고생산 저장/수정
      const itemName =
        resolvedItem?.item_name ||
        `${codeMap?.products.find((p) => p.code === form.prodCode)?.name || form.prodCode} ${codeMap?.specs.find((s) => s.code === form.specCode)?.name || form.specCode}`;

      const saveParams = {
        memo: form.memo,
        regDate: form.regDate,
        targetStockQty: form.quantity,
        bendingLot: {
          lot_number: lotData.lot_number,
          prod_code: form.prodCode,
          spec_code: form.specCode,
          length_code: form.lengthCode,
          raw_lot_no: form.rawLotNo || undefined,
          fabric_lot_no: isSmokeBarrier ? form.fabricLotNo || undefined : undefined,
          material: lotData.material || material,
        },
        item: {
          itemId: resolvedItem?.item_id,
          itemCode: resolvedItem?.item_code || expectedItemCode || undefined,
          itemName,
          specification: resolvedItem?.specification || material,
          quantity: form.quantity,
          unit: resolvedItem?.unit || 'EA',
        },
      };

      const saveResult = isEditMode && initialData
        ? await updateBendingStockOrder(initialData.id, saveParams)
        : await createBendingStockOrder(saveParams);

      if (saveResult.__authError) {
        toast.error('인증이 만료되었습니다.');
        return { success: false, error: '' };
      }
      if (!saveResult.success) {
        return { success: false, error: saveResult.error || '저장에 실패했습니다.' };
      }

      toast.success(isEditMode ? '절곡품 재고생산이 수정되었습니다.' : '절곡품 재고생산이 등록되었습니다.');
      if (saveResult.data?.id) {
        router.push(`${basePath}/${saveResult.data.id}`);
      } else {
        router.push(basePath);
      }
      return { success: true, error: '' };
    } finally {
      setIsSaving(false);
    }
  }, [form, resolvedItem, expectedItemCode, codeMap, material, isSmokeBarrier, router, basePath]);

  // 취소
  const handleCancel = useCallback(() => {
    if (isEditMode && initialData) {
      router.push(`${basePath}/${initialData.id}`);
    } else {
      router.push(basePath);
    }
  }, [isEditMode, initialData, router, basePath]);

  // renderForm
  const renderFormContent = useMemo(
    () => () => (
      <div className="space-y-6">
        {/* 기본 정보 */}
        <FormSection title="기본 정보" icon={ClipboardList}>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="space-y-2">
              <Label>등록일</Label>
              <DatePicker
                value={form.regDate}
                onChange={(date) => setForm((prev) => ({ ...prev, regDate: date }))}
              />
            </div>
            <div className="space-y-2">
              <Label>품목코드</Label>
              <Input
                value={resolvedItem?.item_code || expectedItemCode || initialData?.items?.[0]?.itemCode || ''}
                disabled
                placeholder="품목 선택 시 자동 지정"
                className={resolvedItem?.item_code || expectedItemCode || initialData?.items?.[0]?.itemCode ? 'font-mono font-semibold' : ''}
              />
            </div>
            <div className="space-y-2">
              <Label>수량</Label>
              <NumberInput
                value={form.quantity}
                onChange={(value) =>
                  setForm((prev) => ({ ...prev, quantity: value ?? 1 }))
                }
                min={1}
                placeholder="수량"
              />
            </div>
            <div className="space-y-2">
              <Label>로트번호</Label>
              <Input
                value={isEditMode && initialData?.bendingLot?.lotNumber
                  ? initialData.bendingLot.lotNumber
                  : lotPreview ? `${lotPreview}-___` : '저장 시 자동 생성'}
                disabled
                className="font-mono"
              />
            </div>
          </div>
        </FormSection>

        {/* 품목 선택 (캐스케이딩) */}
        <FormSection title="품목 선택" icon={Layers}>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* 품목명 */}
            <div className="space-y-2">
              <Label>품목명 <span className="text-red-500">*</span></Label>
              <Select
                key={`prod-${form.prodCode}`}
                value={form.prodCode}
                onValueChange={handleProdChange}
              >
                <SelectTrigger>
                  <SelectValue placeholder="품목 선택" />
                </SelectTrigger>
                <SelectContent>
                  {codeMap?.products.map((p) => (
                    <SelectItem key={p.code} value={p.code}>
                      {p.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 종류 */}
            <div className="space-y-2">
              <Label>종류 <span className="text-red-500">*</span></Label>
              <Select
                key={`spec-${form.prodCode}-${form.specCode}`}
                value={form.specCode}
                onValueChange={handleSpecChange}
                disabled={!form.prodCode}
              >
                <SelectTrigger>
                  <SelectValue placeholder="종류 선택" />
                </SelectTrigger>
                <SelectContent>
                  {filteredSpecs.map((s) => (
                    <SelectItem key={s.code} value={s.code}>
                      {s.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 모양&길이 */}
            <div className="space-y-2">
              <Label>모양&길이 <span className="text-red-500">*</span></Label>
              <Select
                key={`length-${form.prodCode}-${form.specCode}-${form.lengthCode}`}
                value={form.lengthCode}
                onValueChange={handleLengthChange}
                disabled={!form.specCode}
              >
                <SelectTrigger>
                  <SelectValue placeholder="모양&길이 선택" />
                </SelectTrigger>
                <SelectContent>
                  {filteredLengths.map((l) => (
                    <SelectItem key={l.code} value={l.code}>
                      {l.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 매핑 결과 */}
          {resolvedItem && (
            <div className="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
              <p className="text-sm font-medium text-green-800">매핑된 품목</p>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2 mt-2 text-sm">
                <div>
                  <span className="text-muted-foreground">품목코드: </span>
                  <code className="bg-green-100 px-1 rounded">{resolvedItem.item_code}</code>
                </div>
                <div>
                  <span className="text-muted-foreground">품목명: </span>
                  {resolvedItem.item_name}
                </div>
                <div>
                  <span className="text-muted-foreground">규격: </span>
                  {resolvedItem.specification}
                </div>
                <div>
                  <span className="text-muted-foreground">단위: </span>
                  {resolvedItem.unit}
                </div>
              </div>
            </div>
          )}
          {resolveError && (
            <div className="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
              <p className="text-sm text-yellow-800">{resolveError}</p>
              <p className="text-xs text-yellow-600 mt-1">
                매핑 없이도 저장 가능합니다. 추후 관리자가 매핑을 등록하면 연결됩니다.
              </p>
            </div>
          )}
        </FormSection>

        {/* LOT 정보 */}
        <FormSection title="LOT 정보" icon={Tag}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>{isEditMode ? '생산품 LOT' : '생산품 LOT (프리뷰)'}</Label>
              <Input
                value={isEditMode && initialData?.bendingLot?.lotNumber
                  ? initialData.bendingLot.lotNumber
                  : lotPreview ? `${lotPreview}-___` : ''}
                disabled
                placeholder="품목/종류/등록일 선택 시 자동 생성"
              />
              {!isEditMode && (
                <p className="text-xs text-muted-foreground">
                  일련번호는 저장 시 자동 확정됩니다
                </p>
              )}
            </div>
            <div className="space-y-2">
              <Label>원자재 재질</Label>
              <Input value={material} disabled placeholder="품목/종류 선택 시 자동 결정" />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
            <div className="space-y-2">
              <Label>원자재(철판) LOT</Label>
              <div className="flex gap-2">
                <Input
                  value={form.rawLotNo}
                  readOnly
                  placeholder="LOT 선택 (선택)"
                  className="flex-1"
                />
                {form.rawLotNo && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="shrink-0"
                    onClick={() => setForm((prev) => ({ ...prev, rawLotNo: '' }))}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                )}
                <Button
                  type="button"
                  variant="outline"
                  className="shrink-0"
                  disabled={!material}
                  onClick={() => setRawLotModalOpen(true)}
                >
                  <Search className="h-4 w-4 mr-1" />
                  선택
                </Button>
              </div>
            </div>
            {isSmokeBarrier && (
              <div className="space-y-2">
                <Label>원단 LOT</Label>
                <div className="flex gap-2">
                  <Input
                    value={form.fabricLotNo}
                    readOnly
                    placeholder="LOT 선택 (선택)"
                    className="flex-1"
                  />
                  {form.fabricLotNo && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="shrink-0"
                      onClick={() => setForm((prev) => ({ ...prev, fabricLotNo: '' }))}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  )}
                  <Button
                    type="button"
                    variant="outline"
                    className="shrink-0"
                    onClick={() => setFabricLotModalOpen(true)}
                  >
                    <Search className="h-4 w-4 mr-1" />
                    선택
                  </Button>
                </div>
              </div>
            )}
          </div>
        </FormSection>

        {/* 메모 */}
        <FormSection title="메모" icon={MessageSquare}>
          <div className="space-y-2">
            <Label>메모</Label>
            <Textarea
              placeholder="메모를 입력하세요 (선택)"
              value={form.memo}
              onChange={(e) =>
                setForm((prev) => ({ ...prev, memo: e.target.value }))
              }
              rows={3}
            />
          </div>
        </FormSection>
      </div>
    ),
    [
      form,
      codeMap,
      filteredSpecs,
      filteredLengths,
      material,
      lotPreview,
      resolvedItem,
      expectedItemCode,
      resolveError,
      isSmokeBarrier,
      isEditMode,
      initialData,
      handleProdChange,
      handleSpecChange,
      handleLengthChange,
    ]
  );

  return (
    <>
      <IntegratedDetailTemplate
        config={config}
        mode={isEditMode ? 'edit' : 'create'}
        isLoading={isLoading}
        onCancel={handleCancel}
        onSubmit={handleSave}
        renderForm={renderFormContent}
      />

      {/* 원자재 LOT 선택 모달 */}
      <MaterialLotModal
        open={rawLotModalOpen}
        onOpenChange={setRawLotModalOpen}
        material={material}
        title="원자재(철판) LOT 선택"
        onSelect={(lotNo) => setForm((prev) => ({ ...prev, rawLotNo: lotNo }))}
      />

      {/* 원단 LOT 선택 모달 (연기차단재 전용) */}
      {isSmokeBarrier && (
        <MaterialLotModal
          open={fabricLotModalOpen}
          onOpenChange={setFabricLotModalOpen}
          material="화이바원단"
          title="원단 LOT 선택"
          onSelect={(lotNo) => setForm((prev) => ({ ...prev, fabricLotNo: lotNo }))}
        />
      )}
    </>
  );
}
