'use client';

import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Banknote,
} 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 { WithdrawalRecord, WithdrawalType, Vendor } from './types';
import { WITHDRAWAL_TYPE_SELECTOR_OPTIONS } from './types';

// ===== Props =====
interface WithdrawalDetailProps {
  withdrawalId: string;
  mode: 'view' | 'edit';
}

// ===== 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' },
];

// ===== 적요 옵션 =====
const NOTE_OPTIONS = [
  { value: '', label: '선택' },
  { value: 'note1', label: '적요 1' },
  { value: 'note2', label: '적요 2' },
  { value: 'note3', label: '적요 3' },
];

// ===== Mock 상세 데이터 조회 =====
const fetchWithdrawalDetail = (id: string): WithdrawalRecord | null => {
  // 실제로는 API 호출
  return {
    id,
    withdrawalDate: '2025-12-12',
    withdrawalAmount: 100000000,
    accountName: '국민 1234 (계좌명)',
    recipientName: '수취인명',
    note: '',
    withdrawalType: 'unset',
    vendorId: '',
    vendorName: '',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
};

export function WithdrawalDetail({ withdrawalId, mode }: WithdrawalDetailProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';

  // ===== 폼 상태 =====
  const [withdrawalDate, setWithdrawalDate] = useState('');
  const [accountName, setAccountName] = useState('');
  const [recipientName, setRecipientName] = useState('');
  const [withdrawalAmount, setWithdrawalAmount] = useState(0);
  const [note, setNote] = useState('');
  const [vendorId, setVendorId] = useState('');
  const [withdrawalType, setWithdrawalType] = useState<WithdrawalType>('unset');
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // ===== 데이터 로드 =====
  useEffect(() => {
    if (withdrawalId) {
      const data = fetchWithdrawalDetail(withdrawalId);
      if (data) {
        setWithdrawalDate(data.withdrawalDate);
        setAccountName(data.accountName);
        setRecipientName(data.recipientName);
        setWithdrawalAmount(data.withdrawalAmount);
        setNote(data.note);
        setVendorId(data.vendorId);
        setWithdrawalType(data.withdrawalType);
      }
    }
  }, [withdrawalId]);

  // ===== 저장 핸들러 =====
  const handleSave = useCallback(() => {
    console.log('저장:', {
      withdrawalId,
      withdrawalDate,
      accountName,
      recipientName,
      withdrawalAmount,
      note,
      vendorId,
      withdrawalType,
    });
    router.push('/ko/accounting/withdrawals');
  }, [withdrawalId, withdrawalDate, accountName, recipientName, withdrawalAmount, note, vendorId, withdrawalType, router]);

  // ===== 취소 핸들러 =====
  const handleCancel = useCallback(() => {
    router.push(`/ko/accounting/withdrawals/${withdrawalId}`);
  }, [router, withdrawalId]);

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

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

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

  return (
    <PageLayout>
      {/* 페이지 헤더 */}
      <PageHeader
        title={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 모드: [취소] [저장] */
          <>
            <Button variant="outline" onClick={handleCancel}>
              취소
            </Button>
            <Button onClick={handleSave} className="bg-orange-500 hover:bg-orange-600">
              저장
            </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="withdrawalDate">출금일</Label>
              <Input
                id="withdrawalDate"
                type="date"
                value={withdrawalDate}
                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="recipientName">수취인명</Label>
              <Input
                id="recipientName"
                value={recipientName}
                readOnly
                disabled
                className="bg-gray-50"
              />
            </div>

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

            {/* 적요 */}
            <div className="space-y-2">
              <Label htmlFor="note">적요</Label>
              <Select value={note} onValueChange={setNote} disabled={isViewMode}>
                <SelectTrigger>
                  <SelectValue placeholder="선택 ▼" />
                </SelectTrigger>
                <SelectContent>
                  {NOTE_OPTIONS.map((option) => (
                    <SelectItem key={option.value || 'empty'} value={option.value || 'empty'}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </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 md:col-span-2">
              <Label htmlFor="withdrawalType">
                출금 유형 <span className="text-red-500">*</span>
              </Label>
              <Select value={withdrawalType} onValueChange={(v) => setWithdrawalType(v as WithdrawalType)} disabled={isViewMode}>
                <SelectTrigger className="md:w-1/2">
                  <SelectValue placeholder="선택 ▼" />
                </SelectTrigger>
                <SelectContent>
                  {WITHDRAWAL_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>
  );
}
