'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Landmark, Save, Trash2, X, Edit, ArrowLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { AccountNumberInput } from '@/components/ui/account-number-input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { useDeleteDialog } from '@/hooks/useDeleteDialog';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { toast } from 'sonner';
import { useMenuStore } from '@/stores/menuStore';
import type { Account, AccountFormData, AccountStatus } from './types';
import {
  BANK_OPTIONS,
  BANK_LABELS,
  ACCOUNT_STATUS_OPTIONS,
  ACCOUNT_STATUS_LABELS,
  ACCOUNT_STATUS_COLORS,
} from './types';
import { createBankAccount, updateBankAccount, deleteBankAccount } from './actions';

interface AccountDetailProps {
  account?: Account;
  mode: 'create' | 'view' | 'edit';
}

export function AccountDetail({ account, mode: initialMode }: AccountDetailProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);
  const [mode, setMode] = useState(initialMode);
  const deleteDialog = useDeleteDialog({
    onDelete: async (id) => deleteBankAccount(Number(id)),
    onSuccess: () => router.push('/ko/settings/accounts'),
    entityName: '계좌',
  });

  // URL에서 mode 파라미터 확인
  useEffect(() => {
    const urlMode = searchParams.get('mode');
    if (urlMode === 'edit' && account) {
      setMode('edit');
    }
  }, [searchParams, account]);

  // 폼 상태
  const [formData, setFormData] = useState<AccountFormData>({
    category: account?.category || 'bank_account',
    accountType: account?.accountType || 'savings',
    bankCode: account?.bankCode || '',
    bankName: account?.bankName || '',
    accountNumber: account?.accountNumber || '',
    accountName: account?.accountName || '',
    accountHolder: account?.accountHolder || '',
    status: account?.status || 'active',
  });

  const isViewMode = mode === 'view';
  const isCreateMode = mode === 'create';
  const isEditMode = mode === 'edit';

  const handleChange = (field: keyof AccountFormData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleBack = () => {
    router.push('/ko/settings/accounts');
  };

  const handleSubmit = async () => {
    const dataToSend = {
      ...formData,
      bankName: BANK_LABELS[formData.bankCode] || formData.bankCode,
    };

    if (isCreateMode) {
      const result = await createBankAccount(dataToSend);
      if (result.success) {
        toast.success('계좌가 등록되었습니다.');
        router.push('/ko/settings/accounts');
      } else {
        toast.error(result.error || '계좌 등록에 실패했습니다.');
      }
    } else {
      if (!account?.id) return;
      const result = await updateBankAccount(account.id, dataToSend);
      if (result.success) {
        toast.success('계좌가 수정되었습니다.');
        router.push('/ko/settings/accounts');
      } else {
        toast.error(result.error || '계좌 수정에 실패했습니다.');
      }
    }
  };

  const handleCancel = () => {
    if (isCreateMode) {
      router.push('/ko/settings/accounts');
    } else {
      setMode('view');
      // 원래 데이터로 복원
      if (account) {
        setFormData({
          category: account.category || 'bank_account',
          accountType: account.accountType || 'savings',
          bankCode: account.bankCode, bankName: account.bankName,
          accountNumber: account.accountNumber,
          accountName: account.accountName,
          accountHolder: account.accountHolder,
          status: account.status,
        });
      }
    }
  };

  const handleEdit = () => {
    setMode('edit');
    // URL도 변경
    if (account?.id) {
      router.push(`/ko/settings/accounts/${account.id}?mode=edit`);
    }
  };

  // 뷰 모드 렌더링
  if (isViewMode) {
    return (
      <PageLayout>
        <PageHeader
          title="계좌 상세"
          description="계좌 정보를 관리합니다"
          icon={Landmark}
        />

        <div className="space-y-6">
          {/* 기본 정보 */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="text-base">기본 정보</CardTitle>
              <Badge className={ACCOUNT_STATUS_COLORS[formData.status]}>
                {ACCOUNT_STATUS_LABELS[formData.status]}
              </Badge>
            </CardHeader>
            <CardContent>
              <dl className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">은행</dt>
                  <dd className="text-sm mt-1">{BANK_LABELS[formData.bankCode] || '-'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">계좌번호</dt>
                  <dd className="text-sm mt-1 font-mono">{formData.accountNumber || '-'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">예금주</dt>
                  <dd className="text-sm mt-1">{formData.accountHolder || '-'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">계좌 비밀번호</dt>
                  <dd className="text-sm mt-1">****</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">계좌명</dt>
                  <dd className="text-sm mt-1">{formData.accountName || '-'}</dd>
                </div>
                <div>
                  <dt className="text-sm font-medium text-muted-foreground">상태</dt>
                  <dd className="text-sm mt-1">
                    <Badge className={ACCOUNT_STATUS_COLORS[formData.status]}>
                      {ACCOUNT_STATUS_LABELS[formData.status]}
                    </Badge>
                  </dd>
                </div>
              </dl>
            </CardContent>
          </Card>

        </div>

        {/* 하단 액션 버튼 (sticky) */}
        <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}>
          <Button variant="outline" onClick={handleBack} size="sm" className="md:size-default">
            <ArrowLeft className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">목록으로</span>
          </Button>
          <div className="flex items-center gap-1 md:gap-2">
            <Button
              variant="outline"
              onClick={() => account?.id && deleteDialog.single.open(String(account.id))}
              size="sm"
              className="text-destructive hover:bg-destructive hover:text-destructive-foreground md:size-default"
            >
              <Trash2 className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">삭제</span>
            </Button>
            <Button onClick={handleEdit} size="sm" className="md:size-default">
              <Edit className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수정</span>
            </Button>
          </div>
        </div>

        {/* 삭제 확인 다이얼로그 */}
        <DeleteConfirmDialog
          open={deleteDialog.single.isOpen}
          onOpenChange={deleteDialog.single.onOpenChange}
          description={
            <>
              계좌를 정말 삭제하시겠습니까?
              <br />
              <span className="text-muted-foreground text-sm">
                삭제된 계좌의 과거 사용 내역은 보존됩니다.
              </span>
            </>
          }
          onConfirm={deleteDialog.single.confirm}
          loading={deleteDialog.isPending}
        />
      </PageLayout>
    );
  }

  // 생성/수정 모드 렌더링
  return (
    <PageLayout>
      <PageHeader
        title={isCreateMode ? '계좌 등록' : '계좌 수정'}
        description="계좌 정보를 관리합니다"
        icon={Landmark}
      />

      <div className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 은행 & 계좌번호 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="bankCode">은행</Label>
                <Select
                  value={formData.bankCode}
                  onValueChange={(value) => handleChange('bankCode', value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="은행 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {BANK_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="accountNumber">계좌번호</Label>
                <AccountNumberInput
                  id="accountNumber"
                  value={formData.accountNumber}
                  onChange={(value) => handleChange('accountNumber', value)}
                  placeholder="1234-1234-1234-1234"
                  disabled={isEditMode} // 수정 시 계좌번호는 변경 불가
                />
              </div>
            </div>

            {/* 예금주 & 계좌 비밀번호 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="accountHolder">예금주</Label>
                <Input
                  id="accountHolder"
                  value={formData.accountHolder}
                  onChange={(e) => handleChange('accountHolder', e.target.value)}
                  placeholder="예금주명"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="accountName">계좌명</Label>
                <Input
                  id="accountName2"
                  value={formData.accountName}
                  onChange={(e) => handleChange('accountName', e.target.value)}
                  placeholder="계좌명"
                  disabled
                />
              </div>
            </div>

            {/* 계좌명 & 상태 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="accountName">계좌명</Label>
                <Input
                  id="accountName"
                  value={formData.accountName}
                  onChange={(e) => handleChange('accountName', e.target.value)}
                  placeholder="계좌명을 입력해주세요"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">상태</Label>
                <Select
                  value={formData.status}
                  onValueChange={(value) => handleChange('status', value as AccountStatus)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="상태 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {ACCOUNT_STATUS_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

      </div>

      {/* 하단 액션 버튼 (sticky) */}
      <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[48px] ${sidebarCollapsed ? 'md:left-[156px]' : 'md:left-[316px]'} flex items-center justify-between`}>
        <Button variant="outline" onClick={handleCancel} size="sm" className="md:size-default">
          <X className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">취소</span>
        </Button>
        <Button onClick={handleSubmit} size="sm" className="md:size-default">
          <Save className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">{isCreateMode ? '등록' : '저장'}</span>
        </Button>
      </div>
    </PageLayout>
  );
}