'use client';

import { useState, useCallback, useMemo, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, Trash2 } from 'lucide-react';
import { ImageUpload } from '@/components/ui/image-upload';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { FileList, type ExistingFile } from '@/components/ui/file-list';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { PhoneInput } from '@/components/ui/phone-input';
import { BusinessNumberInput } from '@/components/ui/business-number-input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { partnerConfig } from './partnerConfig';
import { useDaumPostcode } from '@/hooks/useDaumPostcode';
import { toast } from 'sonner';
import type { Partner, PartnerFormData, PartnerMemo, PartnerDocument } from './types';
import {
  PARTNER_TYPE_OPTIONS,
  CREDIT_RATING_OPTIONS,
  TRANSACTION_GRADE_OPTIONS,
  PAYMENT_DAY_OPTIONS,
  getEmptyPartnerFormData,
  partnerToFormData,
} from './types';
import { createPartner, updatePartner, deletePartner } from './actions';
import { formatNumber } from '@/lib/utils/amount';
import { getLocalDateString } from '@/lib/utils/date';

// 목업 문서 목록 (상세 모드에서 다운로드 버튼 테스트용)
const MOCK_DOCUMENTS: PartnerDocument[] = [
  {
    id: '1',
    fileName: '사업자등록증.pdf',
    fileUrl: '#',
    fileSize: 1024000, // 1MB
    uploadedAt: '2024-12-15T10:00:00',
  },
  {
    id: '2',
    fileName: '통장사본.jpg',
    fileUrl: '#',
    fileSize: 512000, // 500KB
    uploadedAt: '2024-12-16T14:30:00',
  },
  {
    id: '3',
    fileName: '인감증명서.pdf',
    fileUrl: '#',
    fileSize: 768000, // 750KB
    uploadedAt: '2024-12-18T09:00:00',
  },
];

interface PartnerFormProps {
  mode: 'view' | 'edit' | 'new';
  partnerId?: string;
  initialData?: Partner;
}

export default function PartnerForm({ mode, partnerId, initialData }: PartnerFormProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isNewMode = mode === 'new';
  const isEditMode = mode === 'edit';

  // 폼 데이터
  const [formData, setFormData] = useState<PartnerFormData>(
    initialData ? partnerToFormData(initialData) : getEmptyPartnerFormData()
  );

  // 새 메모 입력
  const [newMemo, setNewMemo] = useState('');

  // 상세/수정 모드에서 목데이터 초기화
  useEffect(() => {
    if (initialData) {
      setFormData((prev) => ({
        ...prev,
        // 문서 목데이터
        documents: prev.documents.length === 0 ? MOCK_DOCUMENTS : prev.documents,
        // 회사 로고 목데이터
        logoUrl: prev.logoUrl || prev.logoBlob ? prev.logoUrl : 'https://placehold.co/750x250/f97316/white?text=Company+Logo',
      }));
    }
  }, [initialData]);

  // Daum 우편번호 서비스
  const { openPostcode } = useDaumPostcode({
    onComplete: (result) => {
      setFormData((prev) => ({
        ...prev,
        zipCode: result.zonecode,
        address1: result.address,
      }));
    },
  });

  // 필드 변경 핸들러
  const handleChange = useCallback((field: keyof PartnerFormData, value: unknown) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  // 저장 핸들러 (IntegratedDetailTemplate용)
  const handleSubmit = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    if (!formData.partnerName.trim()) {
      return { success: false, error: '거래처명을 입력해주세요.' };
    }
    try {
      let result;
      if (isNewMode) {
        result = await createPartner(formData);
      } else if (partnerId) {
        result = await updatePartner(partnerId, formData);
      } else {
        return { success: false, error: '거래처 ID가 없습니다.' };
      }

      if (!result.success) {
        return { success: false, error: result.error || '저장에 실패했습니다.' };
      }

      toast.success(isNewMode ? '거래처가 등록되었습니다.' : '수정이 완료되었습니다.');
      router.push('/ko/construction/project/bidding/partners');
      router.refresh();
      return { success: true };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '저장에 실패했습니다.' };
    }
  }, [isNewMode, partnerId, formData, router]);

  // 삭제 핸들러 (IntegratedDetailTemplate용)
  const handleDelete = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    if (!partnerId) {
      return { success: false, error: '거래처 ID가 없습니다.' };
    }
    try {
      const result = await deletePartner(partnerId);

      if (!result.success) {
        return { success: false, error: result.error || '삭제에 실패했습니다.' };
      }

      toast.success('거래처가 삭제되었습니다.');
      router.push('/ko/construction/project/bidding/partners');
      router.refresh();
      return { success: true };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '삭제에 실패했습니다.' };
    }
  }, [partnerId, router]);

  // 메모 추가 핸들러
  const handleAddMemo = useCallback(() => {
    if (!newMemo.trim()) return;
    const now = new Date();
    const dateStr = getLocalDateString(now);
    const timeStr = now.toTimeString().slice(0, 5);
    const memo: PartnerMemo = {
      id: String(Date.now()),
      content: `${dateStr} ${timeStr} [사용자] ${newMemo}`,
      createdAt: now.toISOString(),
    };
    setFormData((prev) => ({
      ...prev,
      memos: [...prev.memos, memo],
    }));
    setNewMemo('');
  }, [newMemo]);

  // 메모 삭제 핸들러
  const handleDeleteMemo = useCallback((memoId: string) => {
    setFormData((prev) => ({
      ...prev,
      memos: prev.memos.filter((m) => m.id !== memoId),
    }));
  }, []);

  // 로고 업로드 핸들러
  const handleLogoUpload = useCallback((file: File) => {
    // BLOB으로 변환
    const reader = new FileReader();
    reader.onload = () => {
      setFormData((prev) => ({
        ...prev,
        logoBlob: reader.result as string,
        logoUrl: null,
      }));
    };
    reader.readAsDataURL(file);
  }, []);

  // 로고 삭제 핸들러
  const handleLogoRemove = useCallback(() => {
    setFormData((prev) => ({
      ...prev,
      logoBlob: null,
      logoUrl: null,
    }));
  }, []);

  // 문서 업로드 핸들러
  const handleDocumentsSelect = useCallback((files: File[]) => {
    const newDocs = files.map((file) => ({
      id: String(Date.now() + Math.random()),
      fileName: file.name,
      fileUrl: URL.createObjectURL(file),
      fileSize: file.size,
      uploadedAt: new Date().toISOString(),
    }));

    setFormData((prev) => ({
      ...prev,
      documents: [...prev.documents, ...newDocs],
    }));
  }, []);

  // 문서 삭제 핸들러
  const handleDocumentRemove = useCallback((docId: string | number) => {
    setFormData((prev) => ({
      ...prev,
      documents: prev.documents.filter((d) => d.id !== docId),
    }));
  }, []);

  // 동적 Config (모드별 타이틀/설명)
  // Note: IntegratedDetailTemplate이 모드에 따라 '등록'/'수정' 자동 추가
  const dynamicConfig = useMemo(() => {
    if (isNewMode) {
      return {
        ...partnerConfig,
        title: '거래처',
        description: '새로운 거래처를 등록합니다',
      };
    }
    if (isEditMode) {
      return {
        ...partnerConfig,
        title: '거래처',
        description: '거래처 정보를 수정합니다',
      };
    }
    return partnerConfig;
  }, [isNewMode, isEditMode]);

  // 입력 필드 렌더링 헬퍼
  const renderField = (
    label: string,
    field: keyof PartnerFormData,
    value: string | number,
    options?: {
      required?: boolean;
      type?: 'text' | 'tel' | 'email' | 'number' | 'phone' | 'businessNumber';
      placeholder?: string;
      disabled?: boolean;
    }
  ) => {
    const { required, type = 'text', placeholder, disabled } = options || {};
    const isDisabled = isViewMode || disabled;
    const stringValue = value !== null && value !== undefined ? String(value) : '';

    const renderInput = () => {
      switch (type) {
        case 'phone':
          return (
            <PhoneInput
              value={stringValue}
              onChange={(v) => handleChange(field, v)}
              placeholder={placeholder}
              disabled={isDisabled}
              className="bg-white"
            />
          );
        case 'businessNumber':
          return (
            <BusinessNumberInput
              value={stringValue}
              onChange={(v) => handleChange(field, v)}
              placeholder={placeholder}
              disabled={isDisabled}
              showValidation
              className="bg-white"
            />
          );
        default:
          return (
            <Input
              type={type === 'tel' ? 'tel' : type}
              value={value}
              onChange={(e) =>
                handleChange(field, type === 'number' ? Number(e.target.value) : e.target.value)
              }
              placeholder={placeholder}
              disabled={isDisabled}
              className="bg-white"
            />
          );
      }
    };

    return (
      <div className="space-y-2">
        <Label className="text-sm font-medium text-gray-700">
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
        {renderInput()}
      </div>
    );
  };

  // 셀렉트 필드 렌더링 헬퍼
  const renderSelectField = (
    label: string,
    field: keyof PartnerFormData,
    value: string,
    options: { value: string; label: string }[],
    required?: boolean
  ) => {
    return (
      <div className="space-y-2">
        <Label className="text-sm font-medium text-gray-700">
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
        <Select value={value} onValueChange={(val) => handleChange(field, val)} disabled={isViewMode}>
          <SelectTrigger className="bg-white">
            <SelectValue placeholder="선택" />
          </SelectTrigger>
          <SelectContent>
            {options.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  };

  // 폼 내용 렌더링 함수 (IntegratedDetailTemplate용)
  const renderFormContent = () => (
    <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">기본 정보 *</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderField('사업자등록번호', 'businessNumber', formData.businessNumber, {
              type: 'businessNumber',
              placeholder: '000-00-00000',
            })}
            {renderField('거래처 코드', 'partnerCode', formData.partnerCode || '', {
              placeholder: '자동생성',
              disabled: true,
            })}
            {renderField('거래처명', 'partnerName', formData.partnerName, { required: true })}
            {renderField('대표자명', 'representative', formData.representative)}
            {renderSelectField('거래처 유형', 'partnerType', formData.partnerType, PARTNER_TYPE_OPTIONS)}
            {renderField('업태', 'businessType', formData.businessType)}
            {renderField('업종', 'businessCategory', formData.businessCategory)}
          </CardContent>
        </Card>

        {/* 연락처 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">연락처 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 주소 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">주소</Label>
              <div className="flex gap-2">
                <Button
                  type="button"
                  variant="outline"
                  disabled={isViewMode}
                  className="shrink-0"
                  onClick={() => openPostcode()}
                >
                  우편번호 찾기
                </Button>
                <Input
                  value={formData.zipCode}
                  onChange={(e) => handleChange('zipCode', e.target.value)}
                  placeholder="우편번호"
                  disabled
                  className="w-[120px] bg-gray-50"
                />
                <Input
                  value={formData.address1}
                  onChange={(e) => handleChange('address1', e.target.value)}
                  placeholder="기본주소"
                  disabled
                  className="flex-1 bg-gray-50"
                />
              </div>
              <Input
                value={formData.address2}
                onChange={(e) => handleChange('address2', e.target.value)}
                placeholder="상세주소"
                disabled={isViewMode}
                className="bg-white"
              />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {renderField('전화번호', 'phone', formData.phone, {
                type: 'phone',
                placeholder: '02-0000-0000',
              })}
              {renderField('모바일', 'mobile', formData.mobile, {
                type: 'phone',
                placeholder: '010-0000-0000',
              })}
              {renderField('팩스', 'fax', formData.fax, {
                type: 'phone',
                placeholder: '02-0000-0000',
              })}
              {renderField('이메일', 'email', formData.email, { type: 'email' })}
            </div>
          </CardContent>
        </Card>

        {/* 담당자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">담당자 정보</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderField('담당자명', 'manager', formData.manager)}
            {renderField('담당자 전화', 'managerPhone', formData.managerPhone, { type: 'phone' })}
            <div className="md:col-span-2">
              {renderField('시스템 관리자', 'systemManager', formData.systemManager)}
            </div>
          </CardContent>
        </Card>

        {/* 회사 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">회사 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 회사 로고 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">회사 로고</Label>
              <ImageUpload
                value={formData.logoBlob || formData.logoUrl}
                onChange={handleLogoUpload}
                onRemove={handleLogoRemove}
                disabled={isViewMode}
                aspectRatio="wide"
                size="lg"
                maxSize={10}
                hint="750 X 250px, 10MB 이하의 PNG, JPEG, GIF"
              />
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {renderSelectField(
                '매출 결제일',
                'salesPaymentDay',
                String(formData.salesPaymentDay || 15),
                PAYMENT_DAY_OPTIONS
              )}
              {renderSelectField('신용등급', 'creditRating', formData.creditRating, CREDIT_RATING_OPTIONS)}
              {renderSelectField(
                '거래등급',
                'transactionGrade',
                formData.transactionGrade,
                TRANSACTION_GRADE_OPTIONS
              )}
              {renderField('세금계산서 이메일', 'taxInvoiceEmail', formData.taxInvoiceEmail, {
                type: 'email',
              })}
            </div>
          </CardContent>
        </Card>

        {/* 추가 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">추가 정보</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 className="text-sm font-medium text-gray-700">미수금</Label>
                <Input
                  type="text"
                  value={formatNumber(formData.outstandingAmount) + '원'}
                  disabled
                  className="bg-gray-50"
                />
              </div>
              {/* 연체 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">연체</Label>
                <div className="flex items-center gap-4">
                  <Input
                    type="text"
                    value={formData.overdueDays ? `${formData.overdueDays}일` : '-'}
                    disabled
                    className="bg-gray-50 flex-1"
                  />
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={formData.overdueToggle}
                      onCheckedChange={(checked) => handleChange('overdueToggle', checked)}
                      disabled={isViewMode}
                    />
                    <span className="text-sm">{formData.overdueToggle ? 'ON' : 'OFF'}</span>
                  </div>
                </div>
              </div>
              {/* 악성채권 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">악성채권</Label>
                <div className="flex items-center gap-4">
                  <div
                    className={`px-3 py-2 rounded-md text-sm flex-1 ${
                      formData.badDebtToggle ? 'bg-red-100 text-red-800' : 'bg-gray-100 text-gray-500'
                    }`}
                  >
                    {formData.badDebtToggle ? '악성채권' : '-'}
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch
                      checked={formData.badDebtToggle}
                      onCheckedChange={(checked) => handleChange('badDebtToggle', checked)}
                      disabled={isViewMode}
                    />
                    <span className="text-sm">{formData.badDebtToggle ? 'ON' : 'OFF'}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* 메모 */}
            <div className="space-y-4 pt-4 border-t">
              <Label className="text-sm font-medium text-gray-700">메모</Label>
              {/* 메모 입력 */}
              {!isViewMode && (
                <div className="flex gap-2">
                  <Textarea
                    value={newMemo}
                    onChange={(e) => setNewMemo(e.target.value)}
                    placeholder="메모를 입력하세요..."
                    className="flex-1 bg-white"
                    rows={2}
                  />
                  <Button
                    type="button"
                    onClick={handleAddMemo}
                    className="bg-blue-500 hover:bg-blue-600 self-end"
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    추가
                  </Button>
                </div>
              )}
              {/* 메모 리스트 */}
              {formData.memos.length > 0 ? (
                <div className="space-y-2">
                  {formData.memos.map((memo) => (
                    <div key={memo.id} className="flex items-start justify-between p-3 bg-gray-50 rounded-lg">
                      <p className="text-sm text-gray-700 flex-1">{memo.content}</p>
                      {!isViewMode && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-6 w-6 text-gray-400 hover:text-red-500"
                          onClick={() => handleDeleteMemo(memo.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-gray-500 text-center py-4">등록된 메모가 없습니다.</p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 필요 서류 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">필요 서류</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!isViewMode && (
              <FileDropzone
                onFilesSelect={handleDocumentsSelect}
                multiple
                maxSize={10}
                title="클릭하여 파일을 첨부하거나, 마우스로 파일을 끌어오세요"
              />
            )}
            <FileList
              existingFiles={formData.documents.map((doc): ExistingFile => ({
                id: doc.id,
                name: doc.fileName,
                url: doc.fileUrl,
                size: doc.fileSize,
              }))}
              onRemoveExisting={isViewMode ? undefined : handleDocumentRemove}
              readOnly={isViewMode}
              emptyMessage="등록된 서류가 없습니다"
            />
          </CardContent>
        </Card>
    </div>
  );

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode={mode === 'new' ? 'create' : mode}
      initialData={{}}
      itemId={partnerId}
      isLoading={false}
      onSubmit={handleSubmit}
      onDelete={partnerId && isViewMode ? handleDelete : undefined}
      renderView={() => renderFormContent()}
      renderForm={() => renderFormContent()}
    />
  );
}