'use client';

import { useState, useCallback, useMemo } from 'react';
import { useDaumPostcode } from '@/hooks/useDaumPostcode';
import { useRouter } from 'next/navigation';
import { Building2, Trash2, Plus, X } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';

// 필드명 매핑
const FIELD_NAME_MAP: Record<string, string> = {
  businessNumber: '사업자등록번호',
  vendorName: '거래처명',
  category: '거래처 유형',
};
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 { 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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import type {
  Vendor,
  VendorCategory,
  CreditRating,
  TransactionGrade,
  BadDebtStatus,
  VendorMemo,
} from './types';
import {
  VENDOR_CATEGORY_SELECTOR_OPTIONS,
  CREDIT_RATING_SELECTOR_OPTIONS,
  TRANSACTION_GRADE_SELECTOR_OPTIONS,
  BAD_DEBT_STATUS_SELECTOR_OPTIONS,
  PAYMENT_DAY_OPTIONS,
  BANK_OPTIONS,
} from './types';

interface VendorDetailProps {
  mode: 'view' | 'edit' | 'new';
  vendorId?: string;
}

// Mock 데이터 가져오기
const getMockVendor = (id: string): Vendor => ({
  id,
  vendorCode: 'V0001',
  businessNumber: '123-12-12345',
  vendorName: '(주)삼성전자',
  representativeName: '홍길동',
  category: 'both',
  businessType: '제조업',
  businessCategory: '전자제품',
  zipCode: '06234',
  address1: '123 서울특별시 서초구 서초대로 123',
  address2: '대한건물 12층 1201호',
  phone: '02-1234-1234',
  mobile: '010-1234-1234',
  fax: '02-1234-1235',
  email: 'abc@email.com',
  managerName: '담당자명',
  managerPhone: '010-1234-1234',
  systemManager: '관리자명',
  logoUrl: '',
  purchasePaymentDay: 10,
  salesPaymentDay: 25,
  creditRating: 'AAA',
  transactionGrade: 'A',
  taxInvoiceEmail: 'abc@email.com',
  bankName: 'kb',
  accountNumber: '12312312313123',
  accountHolder: '예금주명',
  outstandingAmount: 11000000,
  overdueAmount: 0,
  overdueDays: 15,
  unpaidAmount: 11000000,
  badDebtStatus: 'none',
  overdueToggle: false,
  badDebtToggle: false,
  memos: [
    { id: '1', content: '2025-12-12 12:21 [홍길동] 메모 내용', createdAt: '2025-12-12T12:21:00.000Z' },
  ],
  createdAt: '2025-12-18T00:00:00.000Z',
  updatedAt: '2025-12-18T00:00:00.000Z',
});

const getEmptyVendor = (): Omit<Vendor, 'id' | 'createdAt' | 'updatedAt'> => ({
  vendorCode: '',
  businessNumber: '',
  vendorName: '',
  representativeName: '',
  category: 'both',
  businessType: '',
  businessCategory: '',
  zipCode: '',
  address1: '',
  address2: '',
  phone: '',
  mobile: '',
  fax: '',
  email: '',
  managerName: '',
  managerPhone: '',
  systemManager: '',
  logoUrl: '',
  purchasePaymentDay: 10,
  salesPaymentDay: 15,
  creditRating: 'AAA',
  transactionGrade: 'A',
  taxInvoiceEmail: '',
  bankName: 'none',
  accountNumber: '',
  accountHolder: '',
  outstandingAmount: 0,
  overdueAmount: 0,
  overdueDays: 0,
  unpaidAmount: 0,
  badDebtStatus: 'none',
  overdueToggle: false,
  badDebtToggle: false,
  memos: [],
});

export function VendorDetail({ mode, vendorId }: VendorDetailProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isNewMode = mode === 'new';

  // 폼 데이터
  const initialData = vendorId ? getMockVendor(vendorId) : getEmptyVendor();
  const [formData, setFormData] = useState(initialData);

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

  // 다이얼로그 상태
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [showSaveDialog, setShowSaveDialog] = useState(false);

  // Validation 에러 상태
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

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

  // Validation 함수
  const validateForm = useCallback(() => {
    const errors: Record<string, string> = {};

    if (!formData.businessNumber?.trim()) {
      errors.businessNumber = '사업자등록번호를 입력해주세요';
    }
    if (!formData.vendorName?.trim()) {
      errors.vendorName = '거래처명을 입력해주세요';
    }
    if (!formData.category) {
      errors.category = '거래처 유형을 선택해주세요';
    }

    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  }, [formData.businessNumber, formData.vendorName, formData.category]);

  // 필드 변경 핸들러
  const handleChange = useCallback((field: string, value: string | number | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  }, []);

  // 네비게이션 핸들러
  const handleBack = useCallback(() => {
    router.push('/ko/accounting/vendors');
  }, [router]);

  const handleEdit = useCallback(() => {
    router.push(`/ko/accounting/vendors/${vendorId}?mode=edit`);
  }, [router, vendorId]);

  const handleCancel = useCallback(() => {
    if (isNewMode) {
      router.push('/ko/accounting/vendors');
    } else {
      router.push(`/ko/accounting/vendors/${vendorId}`);
    }
  }, [router, vendorId, isNewMode]);

  // 저장 핸들러
  const handleSave = useCallback(() => {
    if (!validateForm()) {
      // 페이지 상단으로 스크롤
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    // 에러 초기화
    setValidationErrors({});
    setShowSaveDialog(true);
  }, [validateForm]);

  const handleConfirmSave = useCallback(() => {
    console.log('저장:', formData);
    setShowSaveDialog(false);
    if (isNewMode) {
      router.push('/ko/accounting/vendors');
    } else {
      router.push(`/ko/accounting/vendors/${vendorId}`);
    }
  }, [formData, router, vendorId, isNewMode]);

  // 삭제 핸들러
  const handleDelete = useCallback(() => {
    setShowDeleteDialog(true);
  }, []);

  const handleConfirmDelete = useCallback(() => {
    console.log('삭제:', vendorId);
    setShowDeleteDialog(false);
    router.push('/ko/accounting/vendors');
  }, [router, vendorId]);

  // 메모 추가 핸들러
  const handleAddMemo = useCallback(() => {
    if (!newMemo.trim()) return;
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 10);
    const timeStr = now.toTimeString().slice(0, 5);
    const memo: VendorMemo = {
      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 headerActions = useMemo(() => {
    if (isViewMode) {
      return (
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleBack}>
            목록
          </Button>
          <Button variant="outline" className="text-red-500 border-red-200 hover:bg-red-50" onClick={handleDelete}>
            삭제
          </Button>
          <Button onClick={handleEdit} className="bg-orange-500 hover:bg-orange-600">
            수정
          </Button>
        </div>
      );
    }
    return (
      <div className="flex gap-2">
        <Button variant="outline" onClick={handleCancel}>
          취소
        </Button>
        <Button onClick={handleSave} className="bg-orange-500 hover:bg-orange-600">
          {isNewMode ? '등록' : '저장'}
        </Button>
      </div>
    );
  }, [isViewMode, isNewMode, handleBack, handleDelete, handleEdit, handleCancel, handleSave]);

  // 입력 필드 렌더링 헬퍼
  const renderField = (
    label: string,
    field: string,
    value: string | number,
    options?: {
      required?: boolean;
      type?: 'text' | 'tel' | 'email' | 'number';
      placeholder?: string;
      disabled?: boolean;
    }
  ) => {
    const { required, type = 'text', placeholder, disabled } = options || {};
    return (
      <div className="space-y-2">
        <Label className="text-sm font-medium text-gray-700">
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
        <Input
          type={type}
          value={value}
          onChange={(e) => handleChange(field, type === 'number' ? Number(e.target.value) : e.target.value)}
          placeholder={placeholder}
          disabled={isViewMode || disabled}
          className="bg-white"
        />
      </div>
    );
  };

  // 셀렉트 필드 렌더링 헬퍼
  const renderSelectField = (
    label: string,
    field: string,
    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>
    );
  };

  return (
    <PageLayout>
      <PageHeader
        title="거래처 상세"
        description="거래처 상세 정보 및 신용등급을 관리합니다"
        icon={Building2}
        actions={headerActions}
        onBack={handleBack}
      />

      <div className="space-y-6">
        {/* Validation 에러 표시 */}
        {Object.keys(validationErrors).length > 0 && (
          <Alert className="bg-red-50 border-red-200">
            <AlertDescription className="text-red-900">
              <div className="flex items-start gap-2">
                <span className="text-lg">⚠️</span>
                <div className="flex-1">
                  <strong className="block mb-2">
                    입력 내용을 확인해주세요 ({Object.keys(validationErrors).length}개 오류)
                  </strong>
                  <ul className="space-y-1 text-sm">
                    {Object.entries(validationErrors).map(([field, message]) => {
                      const fieldName = FIELD_NAME_MAP[field] || field;
                      return (
                        <li key={field} className="flex items-start gap-1">
                          <span>•</span>
                          <span>
                            <strong>{fieldName}</strong>: {message}
                          </span>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            </AlertDescription>
          </Alert>
        )}

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderField('사업자등록번호', 'businessNumber', formData.businessNumber, { required: true, placeholder: '000-00-00000' })}
            {renderField('거래처코드', 'vendorCode', formData.vendorCode, { placeholder: '자동생성' })}
            {renderField('거래처명', 'vendorName', formData.vendorName, { required: true })}
            {renderField('대표자명', 'representativeName', formData.representativeName)}
            {renderSelectField('거래처 유형', 'category', formData.category, VENDOR_CATEGORY_SELECTOR_OPTIONS, true)}
            {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">
                <Input
                  value={formData.zipCode}
                  onChange={(e) => handleChange('zipCode', e.target.value)}
                  placeholder="우편번호"
                  disabled={isViewMode}
                  className="w-[120px] bg-white"
                />
                <Button variant="outline" disabled={isViewMode} onClick={openPostcode} className="shrink-0">
                  우편번호 찾기
                </Button>
              </div>
              <Input
                value={formData.address1}
                onChange={(e) => handleChange('address1', e.target.value)}
                placeholder="기본주소"
                disabled={isViewMode}
                className="bg-white"
              />
              <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: 'tel', placeholder: '02-0000-0000' })}
              {renderField('모바일', 'mobile', formData.mobile, { type: 'tel', placeholder: '010-0000-0000' })}
              {renderField('팩스', 'fax', formData.fax, { type: 'tel', 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('담당자명', 'managerName', formData.managerName)}
            {renderField('담당자 전화', 'managerPhone', formData.managerPhone, { type: 'tel' })}
            {renderField('시스템 관리자', 'systemManager', formData.systemManager)}
          </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="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                <p className="text-sm text-gray-500">750 X 250px, 10MB 이하의 PNG, JPEG, GIF</p>
                {!isViewMode && (
                  <Button variant="outline" className="mt-2">
                    이미지 업로드
                  </Button>
                )}
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {renderSelectField('매입 결제일', 'purchasePaymentDay', String(formData.purchasePaymentDay), PAYMENT_DAY_OPTIONS)}
              {renderSelectField('매출 결제일', 'salesPaymentDay', String(formData.salesPaymentDay), PAYMENT_DAY_OPTIONS)}
            </div>
          </CardContent>
        </Card>

        {/* 신용/거래 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">신용/거래 정보</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderSelectField('신용등급', 'creditRating', formData.creditRating, CREDIT_RATING_SELECTOR_OPTIONS)}
            {renderSelectField('거래등급', 'transactionGrade', formData.transactionGrade, TRANSACTION_GRADE_SELECTOR_OPTIONS)}
            {renderField('세금계산서 이메일', 'taxInvoiceEmail', formData.taxInvoiceEmail, { type: 'email' })}
            {renderSelectField('입금계좌 은행', 'bankName', formData.bankName, BANK_OPTIONS)}
            {renderField('계좌', 'accountNumber', formData.accountNumber, { placeholder: '계좌번호' })}
            {renderField('예금주', 'accountHolder', formData.accountHolder)}
          </CardContent>
        </Card>

        {/* 추가 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">추가 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <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="number"
                  value={formData.outstandingAmount}
                  onChange={(e) => handleChange('outstandingAmount', Number(e.target.value))}
                  disabled={isViewMode}
                  className="bg-white"
                />
              </div>
              {/* 연체 */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium text-gray-700">연체</Label>
                  <Switch
                    checked={formData.overdueToggle}
                    onCheckedChange={(checked) => handleChange('overdueToggle', checked)}
                    disabled={isViewMode}
                    className="data-[state=checked]:bg-orange-500"
                  />
                </div>
                <Input
                  type="number"
                  value={formData.overdueDays}
                  onChange={(e) => handleChange('overdueDays', Number(e.target.value))}
                  disabled={isViewMode}
                  className="bg-white"
                  placeholder="일"
                />
              </div>
              {/* 미지급 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">미지급</Label>
                <Input
                  type="number"
                  value={formData.unpaidAmount}
                  onChange={(e) => handleChange('unpaidAmount', Number(e.target.value))}
                  disabled={isViewMode}
                  className="bg-white"
                />
              </div>
              {/* 악성채권 */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label className="text-sm font-medium text-gray-700">악성채권</Label>
                  <Switch
                    checked={formData.badDebtToggle}
                    onCheckedChange={(checked) => handleChange('badDebtToggle', checked)}
                    disabled={isViewMode}
                    className="data-[state=checked]:bg-orange-500"
                  />
                </div>
                <Select
                  value={formData.badDebtStatus}
                  onValueChange={(val) => handleChange('badDebtStatus', val)}
                  disabled={isViewMode}
                >
                  <SelectTrigger className="bg-white">
                    <SelectValue placeholder="-" />
                  </SelectTrigger>
                  <SelectContent>
                    {BAD_DEBT_STATUS_SELECTOR_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 메모 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">메모</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 메모 입력 */}
            {!isViewMode && (
              <div className="flex gap-2">
                <Textarea
                  value={newMemo}
                  onChange={(e) => setNewMemo(e.target.value)}
                  placeholder="메모를 입력하세요..."
                  className="flex-1 bg-white"
                  rows={2}
                />
                <Button onClick={handleAddMemo} className="bg-orange-500 hover:bg-orange-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
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6 text-gray-400 hover:text-red-500"
                        onClick={() => handleDeleteMemo(memo.id)}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-gray-500 text-center py-4">등록된 메모가 없습니다.</p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>거래처 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              &apos;{formData.vendorName}&apos;을(를) 삭제하시겠습니까?
              <br />
              확인 클릭 시 거래처관리 목록으로 이동합니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 저장 확인 다이얼로그 */}
      <AlertDialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {isNewMode ? '거래처 등록' : '수정 확인'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {isNewMode
                ? '거래처를 등록하시겠습니까?'
                : '정말 수정하시겠습니까? 확인 클릭 시 "수정이 완료되었습니다." 알림이 표시됩니다.'}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmSave}
              className="bg-orange-500 hover:bg-orange-600"
            >
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}