'use client';

import { useState, useCallback, useMemo, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Banknote,
  Save,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 { DepositRecord, DepositType, Vendor } from './types';
import { DEPOSIT_TYPE_SELECTOR_OPTIONS } from './types';

// ===== Props =====
interface DepositDetailProps {
  depositId: string;
  mode: 'view' | 'edit' | 'new';
}

// ===== Mock 거래처 데이터 =====
const MOCK_VENDORS: Vendor[] = [
  { id: 'v1', name: '(주)삼성전자', email: 'samsung@example.com' },
  { id: 'v2', name: '현대자동차', email: 'hyundai@example.com' },
  { id: 'v3', name: 'LG전자', email: 'lg@example.com' },
  { id: 'v4', name: 'SK하이닉스', email: 'skhynix@example.com' },
  { id: 'v5', name: '네이버', email: 'naver@example.com' },
];

// ===== Mock 상세 데이터 조회 =====
const fetchDepositDetail = (id: string): DepositRecord | null => {
  // 실제로는 API 호출
  return {
    id,
    depositDate: '2025-12-12',
    depositAmount: 100000000,
    accountName: '국민은행 1234 (계좌명)',
    depositorName: '홍길동',
    note: '',
    depositType: 'unset',
    vendorId: '',
    vendorName: '',
    status: 'inputWaiting',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
};

export function DepositDetail({ depositId, mode }: DepositDetailProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isNewMode = mode === 'new';

  // ===== 폼 상태 =====
  const [depositDate, setDepositDate] = useState('');
  const [accountName, setAccountName] = useState('');
  const [depositorName, setDepositorName] = useState('');
  const [depositAmount, setDepositAmount] = useState(0);
  const [note, setNote] = useState('');
  const [vendorId, setVendorId] = useState('');
  const [depositType, setDepositType] = useState<DepositType>('unset');
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // ===== 데이터 로드 =====
  useEffect(() => {
    if (depositId) {
      const data = fetchDepositDetail(depositId);
      if (data) {
        setDepositDate(data.depositDate);
        setAccountName(data.accountName);
        setDepositorName(data.depositorName);
        setDepositAmount(data.depositAmount);
        setNote(data.note);
        setVendorId(data.vendorId);
        setDepositType(data.depositType);
      }
    }
  }, [depositId]);

  // ===== 저장 핸들러 =====
  const handleSave = useCallback(() => {
    console.log('저장:', {
      depositId,
      depositDate,
      accountName,
      depositorName,
      depositAmount,
      note,
      vendorId,
      depositType,
    });
    router.push('/ko/accounting/deposits');
  }, [depositId, depositDate, accountName, depositorName, depositAmount, note, vendorId, depositType, router]);

  // ===== 취소 핸들러 =====
  const handleCancel = useCallback(() => {
    if (isNewMode) {
      router.push('/ko/accounting/deposits');
    } else {
      router.push(`/ko/accounting/deposits/${depositId}`);
    }
  }, [router, depositId, isNewMode]);

  // ===== 목록으로 이동 =====
  const handleBack = useCallback(() => {
    router.push('/ko/accounting/deposits');
  }, [router]);

  // ===== 수정 모드로 이동 =====
  const handleEdit = useCallback(() => {
    router.push(`/ko/accounting/deposits/${depositId}?mode=edit`);
  }, [router, depositId]);

  // ===== 삭제 핸들러 =====
  const handleDelete = useCallback(() => {
    console.log('삭제:', depositId);
    setShowDeleteDialog(false);
    router.push('/ko/accounting/deposits');
  }, [depositId, router]);

  return (
    <PageLayout>
      {/* 페이지 헤더 */}
      <PageHeader
        title={isNewMode ? '입금 등록' : isViewMode ? '입금 상세' : '입금 수정'}
        description="입금 상세 내역을 등록합니다"
        icon={Banknote}
      />

      {/* 헤더 액션 버튼 */}
      <div className="flex items-center justify-end gap-2 mb-6">
        {/* view 모드: [목록] [삭제] [수정] */}
        {isViewMode ? (
          <>
            <Button variant="outline" onClick={handleBack}>
              목록
            </Button>
            <Button
              variant="outline"
              className="text-red-500 border-red-200 hover:bg-red-50"
              onClick={() => setShowDeleteDialog(true)}
            >
              삭제
            </Button>
            <Button onClick={handleEdit} className="bg-orange-500 hover:bg-orange-600">
              수정
            </Button>
          </>
        ) : (
          /* edit/new 모드: [취소] [저장/등록] */
          <>
            <Button variant="outline" onClick={handleCancel}>
              취소
            </Button>
            <Button onClick={handleSave} className="bg-orange-500 hover:bg-orange-600">
              {isNewMode ? '등록' : '저장'}
            </Button>
          </>
        )}
      </div>

      {/* 기본 정보 섹션 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="text-lg">기본 정보</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 입금일 */}
            <div className="space-y-2">
              <Label htmlFor="depositDate">입금일</Label>
              <Input
                id="depositDate"
                type="date"
                value={depositDate}
                readOnly
                disabled
                className="bg-gray-50"
              />
            </div>

            {/* 입금계좌 */}
            <div className="space-y-2">
              <Label htmlFor="accountName">입금계좌</Label>
              <Input
                id="accountName"
                value={accountName}
                readOnly
                disabled
                className="bg-gray-50"
              />
            </div>

            {/* 입금자명 */}
            <div className="space-y-2">
              <Label htmlFor="depositorName">입금자명</Label>
              <Input
                id="depositorName"
                value={depositorName}
                readOnly
                disabled
                className="bg-gray-50"
              />
            </div>

            {/* 입금금액 */}
            <div className="space-y-2">
              <Label htmlFor="depositAmount">입금금액</Label>
              <Input
                id="depositAmount"
                value={depositAmount.toLocaleString()}
                readOnly
                disabled
                className="bg-gray-50"
              />
            </div>

            {/* 적요 */}
            <div className="space-y-2 md:col-span-2">
              <Label htmlFor="note">적요</Label>
              <Input
                id="note"
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="적요를 입력해주세요"
                disabled={isViewMode}
              />
            </div>

            {/* 거래처 */}
            <div className="space-y-2">
              <Label htmlFor="vendorId">
                거래처 <span className="text-red-500">*</span>
              </Label>
              <Select value={vendorId} onValueChange={setVendorId} disabled={isViewMode}>
                <SelectTrigger>
                  <SelectValue placeholder="선택 ▼" />
                </SelectTrigger>
                <SelectContent>
                  {MOCK_VENDORS.map((vendor) => (
                    <SelectItem key={vendor.id} value={vendor.id}>
                      {vendor.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 입금 유형 */}
            <div className="space-y-2">
              <Label htmlFor="depositType">
                입금 유형 <span className="text-red-500">*</span>
              </Label>
              <Select value={depositType} onValueChange={(v) => setDepositType(v as DepositType)} disabled={isViewMode}>
                <SelectTrigger>
                  <SelectValue placeholder="선택 ▼" />
                </SelectTrigger>
                <SelectContent>
                  {DEPOSIT_TYPE_SELECTOR_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* ===== 삭제 확인 다이얼로그 ===== */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>입금 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              이 입금 내역을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-red-500 hover:bg-red-600"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}