'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { FileText, Plus, X, Eye, Receipt } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DocumentDetailModal } from '@/components/approval/DocumentDetail';
import type { ProposalDocumentData, ExpenseReportDocumentData } from '@/components/approval/DocumentDetail/types';
import type { PurchaseRecord, PurchaseItem, PurchaseType } from './types';
import { PURCHASE_TYPE_LABELS } from './types';

interface PurchaseDetailProps {
  purchaseId: string;
  mode: 'view' | 'edit' | 'new';
}

// Mock 계좌 목록
const MOCK_ACCOUNTS = [
  { id: '1', bankName: '국민', accountNo: '123-456-789012', alias: '법인계좌' },
  { id: '2', bankName: '신한', accountNo: '110-123-456789', alias: '운영계좌' },
  { id: '3', bankName: '우리', accountNo: '1002-123-456789', alias: '비용계좌' },
];

// Mock 거래처 목록
const MOCK_VENDORS = [
  { id: '1', name: '삼성전자' },
  { id: '2', name: 'LG전자' },
  { id: '3', name: 'SK하이닉스' },
  { id: '4', name: '현대자동차' },
  { id: '5', name: '포스코' },
];

// Mock 데이터 생성 함수
const getMockPurchaseData = (id: string): PurchaseRecord => {
  const index = parseInt(id.replace('purchase-', '')) - 1;
  const vendors = ['삼성전자', 'LG전자', 'SK하이닉스', '현대자동차', '포스코'];
  const purchaseTypes: PurchaseType[] = ['unset', 'raw_material', 'subsidiary_material', 'product', 'outsourcing'];
  const banks = ['국민', '신한', '우리', '하나', 'IBK기업'];
  const supplyAmount = 1500000 + (index * 100000);
  const vat = Math.floor(supplyAmount * 0.1);

  return {
    id,
    purchaseNo: `PUR-2025-${String(index + 1).padStart(4, '0')}`,
    purchaseDate: '2025-12-18',
    vendorId: `vendor-${index % vendors.length}`,
    vendorName: vendors[index % vendors.length],
    supplyAmount,
    vat,
    totalAmount: supplyAmount + vat,
    purchaseType: purchaseTypes[index % purchaseTypes.length],
    evidenceType: 'tax_invoice',
    status: 'completed',
    sourceDocument: index % 3 === 0 ? {
      type: index % 6 === 0 ? 'expense_report' : 'proposal',
      documentNo: `DOC-2025-${String(index + 1).padStart(4, '0')}`,
      title: index % 6 === 0 ? '사무용품 구매 지출결의' : '원자재 구매 품의',
      expectedCost: supplyAmount,
    } : undefined,
    withdrawalAccount: {
      bankName: banks[index % banks.length],
      accountNo: `123-456-${String(789000 + index).padStart(6, '0')}`,
      accountAlias: '법인계좌',
    },
    items: [
      {
        id: `item-${index}-1`,
        itemName: `품목 ${index + 1}-1`,
        quantity: (index % 10) + 1,
        unitPrice: 50000 + (index * 1000),
        supplyPrice: supplyAmount * 0.6,
        vat: vat * 0.6,
        note: '비고',
      },
      {
        id: `item-${index}-2`,
        itemName: `품목 ${index + 1}-2`,
        quantity: (index % 5) + 1,
        unitPrice: 30000 + (index * 500),
        supplyPrice: supplyAmount * 0.4,
        vat: vat * 0.4,
      },
    ],
    taxInvoiceReceived: index % 2 === 0,
    createdAt: '2025-12-18T00:00:00.000Z',
    updatedAt: '2025-12-18T00:00:00.000Z',
  };
};

export function PurchaseDetail({ purchaseId, mode }: PurchaseDetailProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isNewMode = mode === 'new';

  // Mock 데이터 로드
  const initialData = getMockPurchaseData(purchaseId);

  // ===== 로컬 상태 =====
  const [formData, setFormData] = useState<PurchaseRecord>(initialData);
  const [items, setItems] = useState<PurchaseItem[]>(initialData.items);
  const [documentModalOpen, setDocumentModalOpen] = useState(false);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // ===== 핸들러 =====
  const handleFieldChange = useCallback((field: keyof PurchaseRecord, value: unknown) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  }, []);

  const handleAccountChange = useCallback((accountId: string) => {
    const account = MOCK_ACCOUNTS.find(a => a.id === accountId);
    if (account) {
      setFormData(prev => ({
        ...prev,
        withdrawalAccount: {
          bankName: account.bankName,
          accountNo: account.accountNo,
          accountAlias: account.alias,
        },
      }));
    }
  }, []);

  const handleVendorChange = useCallback((vendorId: string) => {
    const vendor = MOCK_VENDORS.find(v => v.id === vendorId);
    if (vendor) {
      setFormData(prev => ({
        ...prev,
        vendorId: vendor.id,
        vendorName: vendor.name,
      }));
    }
  }, []);

  const handleItemChange = useCallback((itemId: string, field: keyof PurchaseItem, value: unknown) => {
    setItems(prev => prev.map(item => {
      if (item.id === itemId) {
        const updated = { ...item, [field]: value };
        // 자동 계산: 공급가액 = 수량 * 단가
        if (field === 'quantity' || field === 'unitPrice') {
          updated.supplyPrice = updated.quantity * updated.unitPrice;
          updated.vat = Math.floor(updated.supplyPrice * 0.1);
        }
        return updated;
      }
      return item;
    }));
  }, []);

  const handleAddItem = useCallback(() => {
    const newItem: PurchaseItem = {
      id: `item-new-${Date.now()}`,
      itemName: '',
      quantity: 1,
      unitPrice: 0,
      supplyPrice: 0,
      vat: 0,
    };
    setItems(prev => [...prev, newItem]);
  }, []);

  const handleRemoveItem = useCallback((itemId: string) => {
    setItems(prev => prev.filter(item => item.id !== itemId));
  }, []);

  const handleSave = useCallback(() => {
    const updatedData: PurchaseRecord = {
      ...formData,
      items,
      updatedAt: new Date().toISOString(),
    };
    console.log('저장:', updatedData);
    // TODO: API 호출
    router.push('/ko/accounting/purchase');
  }, [formData, items, router]);

  const handleBack = useCallback(() => {
    router.push('/ko/accounting/purchase');
  }, [router]);

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

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

  const handleDelete = useCallback(() => {
    console.log('삭제:', purchaseId);
    // TODO: API 호출
    router.push('/ko/accounting/purchase');
  }, [purchaseId, router]);

  // ===== 합계 계산 =====
  const totalSupplyPrice = items.reduce((sum, item) => sum + item.supplyPrice, 0);
  const totalVat = items.reduce((sum, item) => sum + item.vat, 0);
  const totalAmount = totalSupplyPrice + totalVat;

  return (
    <PageLayout>
      {/* 페이지 헤더 */}
      <PageHeader
        title={isNewMode ? '매입 등록' : '매입 상세'}
        description="매입 상세를 등록하고 관리합니다"
        icon={Receipt}
      />

      {/* 헤더 액션 버튼 */}
      <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>

      <div className="space-y-6">
        {/* ===== 기본 정보 섹션 ===== */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 품의서/지출결의서인 경우 전용 레이아웃 */}
            {formData.sourceDocument ? (
              <>
                {/* 문서 타입 및 열람 버튼 */}
                <div className="flex items-center gap-4 p-3 bg-orange-50 border border-orange-200 rounded-lg">
                  <Badge variant="outline" className="bg-orange-100 text-orange-800 border-orange-300">
                    {formData.sourceDocument.type === 'proposal' ? '품의서' : '지출결의서'}
                  </Badge>
                  <span className="text-sm text-muted-foreground">연결된 문서가 있습니다</span>
                  <Button
                    variant="outline"
                    size="sm"
                    className="ml-auto border-orange-300 text-orange-700 hover:bg-orange-100"
                    onClick={() => setDocumentModalOpen(true)}
                  >
                    <Eye className="h-4 w-4 mr-1" />
                    문서 열람
                  </Button>
                </div>

                {/* 품의서/지출결의서용 필드 */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {/* 품의서/지출결의서 제목 */}
                  <div className="space-y-2 col-span-2">
                    <Label>{formData.sourceDocument.type === 'proposal' ? '품의서' : '지출결의서'} 제목</Label>
                    <Input
                      value={formData.sourceDocument.title}
                      readOnly
                      disabled
                      className="bg-gray-50"
                    />
                  </div>

                  {/* 예상비용 */}
                  <div className="space-y-2">
                    <Label>예상비용</Label>
                    <Input
                      value={`${formData.sourceDocument.expectedCost.toLocaleString()}원`}
                      readOnly
                      disabled
                      className="bg-gray-50"
                    />
                  </div>

                  {/* 매입번호 */}
                  <div className="space-y-2">
                    <Label>매입번호</Label>
                    <Input
                      value={formData.purchaseNo}
                      readOnly
                      disabled
                      className="bg-gray-50"
                    />
                  </div>

                  {/* 출금계좌 */}
                  <div className="space-y-2">
                    <Label>출금계좌</Label>
                    <Select
                      value={MOCK_ACCOUNTS.find(a => a.accountNo === formData.withdrawalAccount?.accountNo)?.id || ''}
                      onValueChange={handleAccountChange}
                      disabled={isViewMode}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="계좌 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {MOCK_ACCOUNTS.map((account) => (
                          <SelectItem key={account.id} value={account.id}>
                            {account.bankName} ***{account.accountNo.slice(-4)} ({account.alias})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  {/* 거래처명 */}
                  <div className="space-y-2">
                    <Label>거래처명</Label>
                    <Select
                      value={formData.vendorId}
                      onValueChange={handleVendorChange}
                      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 col-span-2">
                    <Label>매입 유형</Label>
                    <Select
                      value={formData.purchaseType}
                      onValueChange={(value) => handleFieldChange('purchaseType', value as PurchaseType)}
                      disabled={isViewMode}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="매입 유형 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {Object.entries(PURCHASE_TYPE_LABELS).map(([key, label]) => (
                          <SelectItem key={key} value={key}>
                            {label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </>
            ) : (
              /* 일반 매입 (품의서/지출결의서 없는 경우) */
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 매입번호 */}
                <div className="space-y-2">
                  <Label>매입번호</Label>
                  <Input
                    value={formData.purchaseNo}
                    readOnly
                    disabled
                    className="bg-gray-50"
                  />
                </div>

                {/* 매입일 */}
                <div className="space-y-2">
                  <Label>매입일</Label>
                  <Input
                    type="date"
                    value={formData.purchaseDate}
                    onChange={(e) => handleFieldChange('purchaseDate', e.target.value)}
                    disabled={isViewMode}
                  />
                </div>

                {/* 거래처명 */}
                <div className="space-y-2">
                  <Label>거래처명</Label>
                  <Select
                    value={formData.vendorId}
                    onValueChange={handleVendorChange}
                    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>매입 유형</Label>
                  <Select
                    value={formData.purchaseType}
                    onValueChange={(value) => handleFieldChange('purchaseType', value as PurchaseType)}
                    disabled={isViewMode}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="매입 유형 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {Object.entries(PURCHASE_TYPE_LABELS).map(([key, label]) => (
                        <SelectItem key={key} value={key}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* ===== 품목 정보 섹션 ===== */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">품목 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[50px] text-center">#</TableHead>
                    <TableHead>품목명</TableHead>
                    <TableHead className="w-[100px] text-right">수량</TableHead>
                    <TableHead className="w-[120px] text-right">단가</TableHead>
                    <TableHead className="w-[120px] text-right">공급가액</TableHead>
                    <TableHead className="w-[100px] text-right">부가세</TableHead>
                    <TableHead>적요</TableHead>
                    <TableHead className="w-[50px]"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {items.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-center">{index + 1}</TableCell>
                      <TableCell>
                        <Input
                          value={item.itemName}
                          onChange={(e) => handleItemChange(item.id, 'itemName', e.target.value)}
                          placeholder="품목명"
                          disabled={isViewMode}
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={item.quantity || ''}
                          onChange={(e) => handleItemChange(item.id, 'quantity', Number(e.target.value))}
                          className="text-right"
                          disabled={isViewMode}
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={item.unitPrice || ''}
                          onChange={(e) => handleItemChange(item.id, 'unitPrice', Number(e.target.value))}
                          className="text-right"
                          disabled={isViewMode}
                        />
                      </TableCell>
                      <TableCell className="text-right font-medium">
                        {item.supplyPrice.toLocaleString()}
                      </TableCell>
                      <TableCell className="text-right">
                        {item.vat.toLocaleString()}
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.note || ''}
                          onChange={(e) => handleItemChange(item.id, 'note', e.target.value)}
                          placeholder="적요"
                          disabled={isViewMode}
                        />
                      </TableCell>
                      <TableCell>
                        {!isViewMode && items.length > 1 && (
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-red-600 hover:text-red-700"
                            onClick={() => handleRemoveItem(item.id)}
                          >
                            <X className="h-4 w-4" />
                          </Button>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                  {/* 합계 행 */}
                  <TableRow className="bg-gray-50 font-medium">
                    <TableCell colSpan={4} className="text-right">
                      합계
                    </TableCell>
                    <TableCell className="text-right">
                      {totalSupplyPrice.toLocaleString()}
                    </TableCell>
                    <TableCell className="text-right">
                      {totalVat.toLocaleString()}
                    </TableCell>
                    <TableCell colSpan={2}></TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

            {/* 품목 추가 버튼 */}
            {!isViewMode && (
              <div className="mt-4">
                <Button variant="outline" onClick={handleAddItem}>
                  <Plus className="h-4 w-4 mr-2" />
                  추가
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* ===== 세금계산서 섹션 ===== */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">세금계산서</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Label htmlFor="taxInvoice">세금계산서 수취</Label>
                <Switch
                  id="taxInvoice"
                  checked={formData.taxInvoiceReceived}
                  onCheckedChange={(checked) => handleFieldChange('taxInvoiceReceived', checked)}
                  disabled={isViewMode}
                />
              </div>
              <div className="flex items-center gap-2">
                {formData.taxInvoiceReceived ? (
                  <span className="text-sm text-green-600 flex items-center gap-1">
                    <FileText className="h-4 w-4" />
                    수취완료
                  </span>
                ) : (
                  <span className="text-sm text-gray-500 flex items-center gap-1">
                    <FileText className="h-4 w-4" />
                    미수취
                  </span>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* ===== 품의서/지출결의서 문서 열람 모달 ===== */}
      {formData.sourceDocument && (
        <DocumentDetailModal
          open={documentModalOpen}
          onOpenChange={setDocumentModalOpen}
          documentType={formData.sourceDocument.type === 'proposal' ? 'proposal' : 'expenseReport'}
          data={
            formData.sourceDocument.type === 'proposal'
              ? {
                  documentNo: formData.sourceDocument.documentNo,
                  createdAt: formData.createdAt.split('T')[0],
                  vendor: formData.vendorName,
                  vendorPaymentDate: formData.purchaseDate,
                  title: formData.sourceDocument.title,
                  description: '품의 내역 상세',
                  reason: '업무 수행을 위한 필수 구매',
                  estimatedCost: formData.sourceDocument.expectedCost,
                  attachments: [],
                  approvers: [
                    {
                      id: 'approver-1',
                      name: '김팀장',
                      position: '팀장',
                      department: '경영지원팀',
                      status: 'approved',
                      approvedAt: formData.createdAt.split('T')[0],
                    },
                    {
                      id: 'approver-2',
                      name: '이부장',
                      position: '부장',
                      department: '경영지원팀',
                      status: 'approved',
                      approvedAt: formData.createdAt.split('T')[0],
                    },
                  ],
                  drafter: {
                    id: 'drafter-1',
                    name: '홍길동',
                    position: '대리',
                    department: '경영지원팀',
                    status: 'none',
                  },
                } as ProposalDocumentData
              : {
                  documentNo: formData.sourceDocument.documentNo,
                  createdAt: formData.createdAt.split('T')[0],
                  requestDate: formData.purchaseDate,
                  paymentDate: formData.purchaseDate,
                  items: formData.items.map((item, idx) => ({
                    id: item.id,
                    no: idx + 1,
                    description: item.itemName,
                    amount: item.supplyPrice + item.vat,
                    note: item.note || '',
                  })),
                  cardInfo: formData.withdrawalAccount
                    ? `${formData.withdrawalAccount.bankName} ${formData.withdrawalAccount.accountNo}`
                    : '',
                  totalAmount: totalAmount,
                  attachments: [],
                  approvers: [
                    {
                      id: 'approver-1',
                      name: '김팀장',
                      position: '팀장',
                      department: '경영지원팀',
                      status: 'approved',
                      approvedAt: formData.createdAt.split('T')[0],
                    },
                    {
                      id: 'approver-2',
                      name: '이부장',
                      position: '부장',
                      department: '경영지원팀',
                      status: 'approved',
                      approvedAt: formData.createdAt.split('T')[0],
                    },
                  ],
                  drafter: {
                    id: 'drafter-1',
                    name: '홍길동',
                    position: '대리',
                    department: '경영지원팀',
                    status: 'none',
                  },
                } as ExpenseReportDocumentData
          }
          onEdit={() => console.log('문서 수정')}
          onCopy={() => console.log('문서 복제')}
          onApprove={() => console.log('승인')}
          onReject={() => console.log('반려')}
        />
      )}

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