'use client';

import { useState, useRef, useCallback } from 'react';
import { useDaumPostcode } from '@/hooks/useDaumPostcode';
import { Building2, Plus, Save, Upload, X, Search } 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 { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { AddCompanyDialog } from './AddCompanyDialog';
import type { CompanyFormData } from './types';
import { INITIAL_FORM_DATA, PAYMENT_DAY_OPTIONS } from './types';

// Mock 데이터 (실제로는 API에서 가져옴)
const MOCK_COMPANY_DATA: CompanyFormData = {
  companyLogo: undefined,
  companyName: '주식회사 샘플',
  representativeName: '홍길동',
  businessType: '서비스업',
  businessCategory: 'IT',
  zipCode: '01234',
  address: '서울시 강남구 테헤란로',
  addressDetail: '123번지 샘플빌딩 5층',
  email: 'sample@company.com',
  taxInvoiceEmail: 'tax@company.com',
  managerName: '김담당',
  managerPhone: '010-1234-5678',
  businessLicense: 'abc.pdf',
  businessNumber: '123-12-12345',
  paymentBank: '신한은행',
  paymentAccount: '123-1231-23-123',
  paymentAccountHolder: '홍길동',
  paymentDay: '25',
};

export function CompanyInfoManagement() {
  const [isEditMode, setIsEditMode] = useState(false);
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [formData, setFormData] = useState<CompanyFormData>(MOCK_COMPANY_DATA);

  // 파일 input refs
  const logoInputRef = useRef<HTMLInputElement>(null);
  const licenseInputRef = useRef<HTMLInputElement>(null);

  // 로고 파일명
  const [logoFileName, setLogoFileName] = useState<string>('');
  // 사업자등록증 파일명
  const [licenseFileName, setLicenseFileName] = useState<string>(
    typeof MOCK_COMPANY_DATA.businessLicense === 'string'
      ? MOCK_COMPANY_DATA.businessLicense
      : ''
  );

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

  const handleLogoUpload = () => {
    logoInputRef.current?.click();
  };

  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // 파일 크기 체크 (10MB)
      if (file.size > 10 * 1024 * 1024) {
        alert('파일 크기는 10MB 이하여야 합니다.');
        return;
      }
      // 파일 타입 체크
      if (!['image/png', 'image/jpeg', 'image/gif'].includes(file.type)) {
        alert('PNG, JPEG, GIF 파일만 업로드 가능합니다.');
        return;
      }
      setFormData(prev => ({ ...prev, companyLogo: file }));
      setLogoFileName(file.name);
    }
  };

  const handleRemoveLogo = () => {
    setFormData(prev => ({ ...prev, companyLogo: undefined }));
    setLogoFileName('');
    if (logoInputRef.current) {
      logoInputRef.current.value = '';
    }
  };

  const handleLicenseUpload = () => {
    licenseInputRef.current?.click();
  };

  const handleLicenseChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setFormData(prev => ({ ...prev, businessLicense: file }));
      setLicenseFileName(file.name);
    }
  };

  const handleRemoveLicense = () => {
    setFormData(prev => ({ ...prev, businessLicense: undefined }));
    setLicenseFileName('');
    if (licenseInputRef.current) {
      licenseInputRef.current.value = '';
    }
  };

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

  const handleAddressSearch = () => {
    openPostcode();
  };

  const handleSave = async () => {
    // TODO: API 연동
    console.log('저장:', formData);
    setIsEditMode(false);
  };

  const handleCancel = () => {
    setFormData(MOCK_COMPANY_DATA);
    setIsEditMode(false);
  };

  return (
    <PageLayout>
      <PageHeader
        title="회사정보"
        description="회사 정보를 관리합니다"
        icon={Building2}
      />

      {/* 헤더 액션 버튼 */}
      <div className="flex justify-end gap-2 mb-4">
        <Button onClick={() => setShowAddDialog(true)}>
          <Plus className="w-4 h-4 mr-2" />
          회사 추가
        </Button>
        {!isEditMode && (
          <Button variant="outline" onClick={() => setIsEditMode(true)}>
            수정
          </Button>
        )}
      </div>

      <div className="space-y-6">
        {/* 회사 정보 섹션 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">회사 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 회사 로고 */}
            <div className="space-y-2">
              <Label>회사 로고</Label>
              <div className="flex items-start gap-4">
                <div className="w-[200px] h-[67px] border rounded-lg flex items-center justify-center bg-muted/50 overflow-hidden">
                  {logoFileName ? (
                    <span className="text-sm text-muted-foreground truncate px-2">
                      {logoFileName}
                    </span>
                  ) : (
                    <span className="text-sm text-muted-foreground">IMG</span>
                  )}
                </div>
                {isEditMode && (
                  <div className="flex flex-col gap-2">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={handleLogoUpload}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      업로드
                    </Button>
                    {logoFileName && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={handleRemoveLogo}
                      >
                        <X className="w-4 h-4 mr-2" />
                        삭제
                      </Button>
                    )}
                  </div>
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                750 X 250px, 10MB 이하의 PNG, JPEG, GIF
              </p>
              <input
                ref={logoInputRef}
                type="file"
                accept="image/png,image/jpeg,image/gif"
                className="hidden"
                onChange={handleLogoChange}
              />
            </div>

            {/* 회사명 / 대표자명 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="companyName">회사명</Label>
                <Input
                  id="companyName"
                  value={formData.companyName}
                  onChange={(e) => handleChange('companyName', e.target.value)}
                  placeholder="회사명"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="representativeName">대표자명</Label>
                <Input
                  id="representativeName"
                  value={formData.representativeName}
                  onChange={(e) => handleChange('representativeName', e.target.value)}
                  placeholder="대표자명"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 업태 / 업종 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="businessType">업태</Label>
                <Input
                  id="businessType"
                  value={formData.businessType}
                  onChange={(e) => handleChange('businessType', e.target.value)}
                  placeholder="업태명"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="businessCategory">업종</Label>
                <Input
                  id="businessCategory"
                  value={formData.businessCategory}
                  onChange={(e) => handleChange('businessCategory', e.target.value)}
                  placeholder="업종명"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 주소 */}
            <div className="space-y-2">
              <Label>주소</Label>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleAddressSearch}
                    disabled={!isEditMode}
                  >
                    우편번호 찾기
                  </Button>
                  <Input
                    value={formData.zipCode ? `${formData.zipCode} ${formData.address}` : ''}
                    placeholder="주소명"
                    disabled
                    className="flex-1"
                  />
                </div>
                <Input
                  value={formData.addressDetail}
                  onChange={(e) => handleChange('addressDetail', e.target.value)}
                  placeholder="상세주소"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 이메일 / 세금계산서 이메일 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="email">이메일 (아이디)</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleChange('email', e.target.value)}
                  placeholder="abc@email.com"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="taxInvoiceEmail">세금계산서 이메일</Label>
                <Input
                  id="taxInvoiceEmail"
                  type="email"
                  value={formData.taxInvoiceEmail}
                  onChange={(e) => handleChange('taxInvoiceEmail', e.target.value)}
                  placeholder="abc@email.com"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 담당자명 / 담당자 연락처 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="managerName">담당자명</Label>
                <Input
                  id="managerName"
                  value={formData.managerName}
                  onChange={(e) => handleChange('managerName', e.target.value)}
                  placeholder="담당자명"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="managerPhone">담당자 연락처</Label>
                <Input
                  id="managerPhone"
                  value={formData.managerPhone}
                  onChange={(e) => handleChange('managerPhone', e.target.value)}
                  placeholder="010-1234-1234"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 사업자등록증 / 사업자등록번호 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label>사업자등록증</Label>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleLicenseUpload}
                    disabled={!isEditMode}
                  >
                    찾기
                  </Button>
                  {licenseFileName && (
                    <div className="flex items-center gap-2">
                      <span className="text-sm">{licenseFileName}</span>
                      {isEditMode && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={handleRemoveLicense}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      )}
                    </div>
                  )}
                </div>
                <input
                  ref={licenseInputRef}
                  type="file"
                  accept=".pdf,.jpg,.jpeg,.png"
                  className="hidden"
                  onChange={handleLicenseChange}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="businessNumber">사업자등록번호</Label>
                <Input
                  id="businessNumber"
                  value={formData.businessNumber}
                  onChange={(e) => handleChange('businessNumber', e.target.value)}
                  placeholder="123-12-12345"
                  disabled={!isEditMode}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 결제 계좌 정보 섹션 */}
        <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="paymentBank">결제 은행</Label>
                <Input
                  id="paymentBank"
                  value={formData.paymentBank}
                  onChange={(e) => handleChange('paymentBank', e.target.value)}
                  placeholder="은행명"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="paymentAccount">계좌</Label>
                <Input
                  id="paymentAccount"
                  value={formData.paymentAccount}
                  onChange={(e) => handleChange('paymentAccount', e.target.value)}
                  placeholder="123-1231-23-123"
                  disabled={!isEditMode}
                />
              </div>
            </div>

            {/* 예금주 / 결제일 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="paymentAccountHolder">예금주</Label>
                <Input
                  id="paymentAccountHolder"
                  value={formData.paymentAccountHolder}
                  onChange={(e) => handleChange('paymentAccountHolder', e.target.value)}
                  placeholder="예금주명"
                  disabled={!isEditMode}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="paymentDay">결제일</Label>
                {isEditMode ? (
                  <Select
                    value={formData.paymentDay}
                    onValueChange={(value) => handleChange('paymentDay', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="결제일 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {PAYMENT_DAY_OPTIONS.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <Input
                    id="paymentDay"
                    value={
                      PAYMENT_DAY_OPTIONS.find(o => o.value === formData.paymentDay)?.label ||
                      formData.paymentDay
                    }
                    disabled
                  />
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 수정 모드 버튼 */}
        {isEditMode && (
          <div className="flex items-center justify-end gap-2">
            <Button variant="outline" onClick={handleCancel}>
              <X className="w-4 h-4 mr-2" />
              취소
            </Button>
            <Button onClick={handleSave}>
              <Save className="w-4 h-4 mr-2" />
              저장
            </Button>
          </div>
        )}
      </div>

      {/* 회사 추가 다이얼로그 */}
      <AddCompanyDialog
        open={showAddDialog}
        onOpenChange={setShowAddDialog}
      />
    </PageLayout>
  );
}