'use client';

/**
 * 기초관리 등록/수정 폼 — 별도 페이지 (2열 레이아웃)
 *
 * 좌측: 기본 정보 (4열 그리드) + 절곡 입력 테이블
 * 우측: 형상 이미지 + 비고 + 저장 버튼
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { X, Save, Trash2, Loader2, Pencil, History } from 'lucide-react';
import { DrawingCanvas } from '@/components/items/DrawingCanvas';
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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent } from '@/components/ui/card';
import { DatePicker } from '@/components/ui/date-picker';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner';
import { useMenuStore } from '@/stores/menuStore';
import { BendingTable } from './BendingTable';
import {
  getBendingItem,
  getBendingItemFilters,
  createBendingItem,
  updateBendingItem,
  deleteBendingItem,
} from './actions';
import {
  type BendingItem,
  type BendingItemFilters,
  type BendingData,
  type BendingItemFormData,
  recalculateSums,
  createEmptyBendingData,
  getWidthSum,
  getBendCount,
} from './types';

interface BendingBaseFormProps {
  id?: string;
  mode: 'new' | 'edit' | 'view';
}

const INITIAL_FORM: BendingItemFormData = {
  code: '',
  name: '',
  item_name: '',
  item_sep: '',
  item_bending: '',
  material: '',
  item_spec: '120*70',
  model_name: '',
  model_UA: '',
  registration_date: new Date().toISOString().split('T')[0],
  search_keyword: '',
  memo: '',
  exit_direction: '',
  front_bottom_width: '',
  rail_width: '',
  box_width: '',
  box_height: '',
  bendingData: Array.from({ length: 7 }, (_, i) => createEmptyBendingData(i + 1)),
};

export function BendingBaseForm({ id, mode }: BendingBaseFormProps) {
  const router = useRouter();
  const isNew = mode === 'new';
  const isView = mode === 'view';
  const isEdit = mode === 'edit';

  const [formData, setFormData] = useState<BendingItemFormData>(INITIAL_FORM);
  const [bendingData, setBendingData] = useState<BendingData[]>(INITIAL_FORM.bendingData);
  const [filters, setFilters] = useState<BendingItemFilters | null>(null);
  const [isLoading, setIsLoading] = useState(!isNew);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDrawingOpen, setIsDrawingOpen] = useState(false);
  const [drawingImage, setDrawingImage] = useState<string | null>(null);
  const [isHistoryOpen, setIsHistoryOpen] = useState(false);
  const [originalItem, setOriginalItem] = useState<BendingItem | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 파일 선택 → data URL로 미리보기
  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      setDrawingImage(ev.target?.result as string);
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  }, []);

  // 로그인 사용자 이름 로드
  const [authorName, setAuthorName] = useState('');
  useEffect(() => {
    try {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        const user = JSON.parse(userStr);
        if (user?.name) setAuthorName(user.name);
      }
    } catch { /* ignore */ }
  }, []);

  // 데이터 로드
  useEffect(() => {
    getBendingItemFilters().then((r) => {
      if (r.success && r.data) setFilters(r.data as BendingItemFilters);
    });

    // 다른이름저장: sessionStorage에서 데이터 복사 → 새 등록 폼
    if (isNew) {
      try {
        const saved = sessionStorage.getItem('bending-save-as');
        if (saved) {
          const data = JSON.parse(saved);
          sessionStorage.removeItem('bending-save-as');
          setFormData((prev) => ({
            ...prev,
            name: data.name || '',
            item_name: data.name || '',
            material: data.material || '',
          }));
          if (data.bendingData?.length) {
            setBendingData(recalculateSums(data.bendingData));
          }
        }
      } catch { /* ignore */ }
    }

    if (!isNew && id) {
      getBendingItem(id).then((r) => {
        if (r.success && r.data) {
          const item = r.data as BendingItem;
          setOriginalItem(item);
          setFormData({
            code: item.code || '',
            name: item.name || '',
            item_name: item.item_name || '',
            item_sep: item.item_sep || '',
            item_bending: item.item_bending || '',
            material: item.material || '',
            item_spec: item.item_spec || '',
            model_name: item.model_name || '',
            model_UA: item.model_UA || '',
            registration_date: item.registration_date || '',
            search_keyword: item.search_keyword || '',
            memo: item.memo || '',
            exit_direction: item.exit_direction || '',
            front_bottom_width: item.front_bottom_width ? String(item.front_bottom_width) : '',
            rail_width: item.rail_width ? String(item.rail_width) : '',
            box_width: item.box_width ? String(item.box_width) : '',
            box_height: item.box_height ? String(item.box_height) : '',
            bendingData: item.bendingData || [],
          });
          if (item.author) {
            setAuthorName(item.author);
          }
          if (item.image_url) {
            setDrawingImage(item.image_url);
          }
          setBendingData(
            item.bendingData?.length
              ? recalculateSums(item.bendingData)
              : Array.from({ length: 7 }, (_, i) => createEmptyBendingData(i + 1))
          );
        } else {
          toast.error('해당 기초자료가 존재하지 않습니다. (삭제되었거나 연결이 끊어졌을 수 있습니다)');
          router.back();
        }
        setIsLoading(false);
      });
    }
  }, [id, isNew, router]);

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

  const handleBendingDataChange = useCallback((data: BendingData[]) => {
    setBendingData(data);
  }, []);

  // 저장
  const handleSubmit = useCallback(async () => {
    if (!formData.code || !formData.name || !formData.item_name || !formData.item_sep) {
      toast.error('필수 항목을 입력해주세요. (코드, 이름, 품명, 대분류)');
      return;
    }
    if (!formData.item_bending || !formData.material) {
      toast.error('분류와 재질을 입력해주세요.');
      return;
    }

    setIsSaving(true);
    try {
      const payload = {
        ...formData,
        author: authorName,
        bendingData: bendingData.filter((d) => d.input > 0),
        width_sum: getWidthSum(bendingData),
        bend_count: getBendCount(bendingData),
      };

      const result = isNew
        ? await createBendingItem(payload)
        : await updateBendingItem(id!, payload);

      if (result.success) {
        toast.success(isNew ? '등록되었습니다.' : '저장되었습니다.');
        router.push('/production/bending');
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  }, [formData, bendingData, isNew, id, router]);

  // 삭제
  const handleDelete = useCallback(async () => {
    if (!id) return;
    setIsDeleting(true);
    try {
      const result = await deleteBendingItem(id);
      if (result.success) {
        toast.success('삭제되었습니다.');
        router.push('/production/bending');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsDeleting(false);
      setIsDeleteOpen(false);
    }
  }, [id, router]);

  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const disabled = isView;
  const isCase = formData.item_bending === '케이스';

  return (
    <div className="space-y-4 pb-24">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">
          기초자료 {isNew ? '등록' : '수정'}
          {!isNew && formData.code && (
            <span className="ml-2 text-muted-foreground font-normal text-base">{formData.code}</span>
          )}
        </h1>
        <Button variant="link" className="text-muted-foreground" onClick={() => router.push('/production/bending')}>
          ← 목록으로
        </Button>
      </div>

      {/* 2열 레이아웃 */}
      <div className="flex gap-4">
        {/* 좌측: 기본 정보 + 절곡 테이블 */}
        <div className="flex-1 space-y-4">
          <Card>
            <CardContent className="pt-6">
              <h3 className="text-sm font-semibold mb-4">기본 정보</h3>
              {/* 1행 */}
              <div className="grid grid-cols-4 gap-3 mb-3">
                <div className="space-y-1">
                  <Label className="text-xs">코드 <span className="text-red-500">*</span></Label>
                  <Input value={formData.code} onChange={(e) => handleChange('code', e.target.value)} disabled={disabled || isEdit} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">이름 <span className="text-red-500">*</span></Label>
                  <Input value={formData.name} onChange={(e) => handleChange('name', e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">품명 <span className="text-red-500">*</span></Label>
                  <Input value={formData.item_name} onChange={(e) => handleChange('item_name', e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">대분류 <span className="text-red-500">*</span></Label>
                  <Select
                    key={`sep-${formData.item_sep}`}
                    value={formData.item_sep}
                    onValueChange={(v) => handleChange('item_sep', v)}
                    disabled={disabled}
                  >
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="스크린">스크린</SelectItem>
                      <SelectItem value="철재">철재</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 2행 */}
              <div className="grid grid-cols-4 gap-3 mb-3">
                <div className="space-y-1">
                  <Label className="text-xs">분류 <span className="text-red-500">*</span></Label>
                  <Input
                    value={formData.item_bending}
                    onChange={(e) => handleChange('item_bending', e.target.value)}
                    disabled={disabled}
                    list="bending-list"
                  />
                  {filters && (
                    <datalist id="bending-list">
                      {filters.item_bending.map((v) => <option key={v} value={v} />)}
                    </datalist>
                  )}
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">재질 <span className="text-red-500">*</span></Label>
                  <Input
                    value={formData.material}
                    onChange={(e) => handleChange('material', e.target.value)}
                    disabled={disabled}
                    list="material-list"
                  />
                  {filters && (
                    <datalist id="material-list">
                      {filters.material.map((v) => <option key={v} value={v} />)}
                    </datalist>
                  )}
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">규격</Label>
                  <Input value={formData.item_spec} onChange={(e) => handleChange('item_spec', e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">모델</Label>
                  <Input
                    value={formData.model_name}
                    onChange={(e) => handleChange('model_name', e.target.value)}
                    disabled={disabled}
                    list="model-list"
                  />
                  {filters && (
                    <datalist id="model-list">
                      {filters.model_name.map((v) => <option key={v} value={v} />)}
                    </datalist>
                  )}
                </div>
              </div>

              {/* 3행 */}
              <div className="grid grid-cols-4 gap-3 mb-3">
                <div className="space-y-1">
                  <Label className="text-xs">인정여부</Label>
                  <Select
                    key={`ua-${formData.model_UA}`}
                    value={formData.model_UA}
                    onValueChange={(v) => handleChange('model_UA', v)}
                    disabled={disabled}
                  >
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="인정">인정</SelectItem>
                      <SelectItem value="비인정">비인정</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">등록일</Label>
                  <DatePicker
                    value={formData.registration_date}
                    onChange={(v) => handleChange('registration_date', v)}
                    disabled={disabled}
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">작성자</Label>
                  <Input value={authorName} onChange={(e) => setAuthorName(e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">검색어</Label>
                  <Input value={formData.search_keyword} onChange={(e) => handleChange('search_keyword', e.target.value)} disabled={disabled} />
                </div>
              </div>

            </CardContent>
          </Card>

          {/* 케이스 전용 */}
          {isCase && (
            <Card>
              <CardContent className="pt-6">
                <h3 className="text-sm font-semibold mb-4">케이스 전용</h3>
                <div className="grid grid-cols-5 gap-3">
                  <div className="space-y-1">
                    <Label className="text-xs">점검구 방향</Label>
                    <Select
                      key={`exit-${formData.exit_direction}`}
                      value={formData.exit_direction}
                      onValueChange={(v) => handleChange('exit_direction', v)}
                      disabled={disabled}
                    >
                      <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="양면">양면</SelectItem>
                        <SelectItem value="후면">후면</SelectItem>
                        <SelectItem value="밑면">밑면</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">전면밑 (mm)</Label>
                    <Input type="number" value={formData.front_bottom_width} onChange={(e) => handleChange('front_bottom_width', e.target.value)} disabled={disabled} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">레일폭 (mm)</Label>
                    <Input type="number" value={formData.rail_width} onChange={(e) => handleChange('rail_width', e.target.value)} disabled={disabled} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">케이스 너비 (mm)</Label>
                    <Input type="number" value={formData.box_width} onChange={(e) => handleChange('box_width', e.target.value)} disabled={disabled} />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">케이스 높이 (mm)</Label>
                    <Input type="number" value={formData.box_height} onChange={(e) => handleChange('box_height', e.target.value)} disabled={disabled} />
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 절곡 입력 테이블 */}
          <Card>
            <CardContent className="pt-6">
              <BendingTable
                data={bendingData}
                onChange={handleBendingDataChange}
                readOnly={disabled}
                showActions={!disabled}
                showSummary
              />
            </CardContent>
          </Card>
        </div>

        {/* 우측: 이미지 + 비고 + 저장 */}
        <div className="w-[280px] space-y-4">
          {/* 형상 이미지 */}
          <Card>
            <CardContent className="pt-6">
              <h3 className="text-sm font-semibold mb-3">형상 이미지</h3>
              <div className="w-full aspect-square bg-muted/30 border-2 border-dashed rounded-lg flex items-center justify-center mb-3 overflow-hidden">
                {drawingImage ? (
                  <img src={drawingImage} alt="형상 이미지" className="w-full h-full object-contain" />
                ) : (
                  <span className="text-sm text-muted-foreground">이미지 없음</span>
                )}
              </div>
              {!disabled && (
                <div className="space-y-2">
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => fileInputRef.current?.click()}>
                      파일 선택
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="text-xs"
                      onClick={() => setIsDrawingOpen(true)}
                    >
                      <Pencil className="h-3 w-3 mr-1" />
                      그리기
                    </Button>
                  </div>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleFileChange}
                  />
                  <p className="text-xs text-muted-foreground">Ctrl+V로 붙여넣기 가능</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 비고 */}
          <Card>
            <CardContent className="pt-6">
              <h3 className="text-sm font-semibold mb-3">비고</h3>
              <Textarea
                value={formData.memo}
                onChange={(e) => handleChange('memo', e.target.value)}
                disabled={disabled}
                rows={5}
                placeholder="비고를 입력하세요"
              />
            </CardContent>
          </Card>

        </div>
      </div>

      {/* 하단 Sticky 액션 바 */}
      <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[24px] ${sidebarCollapsed ? 'md:left-[120px]' : 'md:left-[280px]'}`}>
        <div className="flex items-center justify-between">
          <Button variant="outline" onClick={() => router.push('/production/bending')} size="sm" className="md:size-default">
            <X className="w-4 h-4 md:mr-2" />
            <span className="hidden md:inline">취소</span>
          </Button>
          <div className="flex items-center gap-1 md:gap-2">
            {isEdit && (
              <>
                <Button variant="outline" size="sm" className="md:size-default" onClick={() => setIsHistoryOpen(true)}>
                  <History className="w-4 h-4 md:mr-2" />
                  <span className="hidden md:inline">이력</span>
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="text-destructive hover:bg-destructive hover:text-destructive-foreground md:size-default"
                  onClick={() => setIsDeleteOpen(true)}
                >
                  <Trash2 className="w-4 h-4 md:mr-2" />
                  <span className="hidden md:inline">삭제</span>
                </Button>
              </>
            )}
            {!disabled && (
              <Button onClick={handleSubmit} disabled={isSaving} size="sm" className="md:size-default">
                {isSaving ? <Loader2 className="w-4 h-4 md:mr-2 animate-spin" /> : <Save className="w-4 h-4 md:mr-2" />}
                <span className="hidden md:inline">저장</span>
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 수정 이력 */}
      <Dialog open={isHistoryOpen} onOpenChange={setIsHistoryOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>수정 이력</DialogTitle>
          </DialogHeader>
          <div className="space-y-3 text-sm">
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">코드</span>
              <span className="font-medium">{originalItem?.code || formData.code}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">등록일</span>
              <span>{originalItem?.registration_date || formData.registration_date || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">작성자</span>
              <span>{originalItem?.author || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">최종수정자</span>
              <span>{originalItem?.modified_by || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">현재 수정자</span>
              <span className="text-blue-600 font-medium">{authorName || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">생성일시</span>
              <span>{originalItem?.created_at || '-'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">수정일시</span>
              <span>{originalItem?.updated_at || '-'}</span>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 그리기 도구 */}
      <DrawingCanvas
        open={isDrawingOpen}
        onOpenChange={setIsDrawingOpen}
        onSave={(imageData) => {
          setDrawingImage(imageData);
          setIsDrawingOpen(false);
        }}
        initialImage={drawingImage || undefined}
        title="절곡 형상 그리기"
        description="절곡 부품의 형상을 그리거나 편집합니다."
      />

      {/* 삭제 확인 */}
      <DeleteConfirmDialog
        open={isDeleteOpen}
        onOpenChange={setIsDeleteOpen}
        onConfirm={handleDelete}
        loading={isDeleting}
        title="기초자료 삭제"
        description="해당 기초자료를 삭제하시겠습니까?"
      />
    </div>
  );
}
