'use client';

import { useEffect, useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { DatePicker } from '@/components/ui/date-picker';
import { CurrencyInput } from '@/components/ui/currency-input';
import { format } from 'date-fns';
import { formatNumber } from '@/lib/utils/amount';
import { getCompanyAutoFill } from './form-actions';
import type { QuotationData, QuotationItem } from './types';

interface QuotationFormProps {
  data: QuotationData;
  onChange: (data: QuotationData) => void;
}

function createEmptyItem(): QuotationItem {
  return {
    id: `item-${Date.now()}`,
    name: '',
    specification: '',
    quantity: 1,
    unitPrice: 0,
    supplyAmount: 0,
    tax: 0,
    note: '',
  };
}

function calcItem(item: QuotationItem, autoTax: boolean): QuotationItem {
  const supplyAmount = item.quantity * item.unitPrice;
  const tax = autoTax ? Math.round(supplyAmount * 0.1) : 0;
  return { ...item, supplyAmount, tax };
}

export function QuotationForm({ data, onChange }: QuotationFormProps) {
  const [isLoadingCompany, setIsLoadingCompany] = useState(false);

  // 공급자(회사) 정보 자동입력
  useEffect(() => {
    async function loadCompanyInfo() {
      setIsLoadingCompany(true);
      const result = await getCompanyAutoFill();
      if (result.success && result.data) {
        const c = result.data;
        onChange({
          ...data,
          businessNumber: data.businessNumber || c.businessNumber,
          companyName: data.companyName || c.companyName,
          representativeName: data.representativeName || c.representativeName,
          companyAddress: data.companyAddress || c.address,
          businessType: data.businessType || c.businessType,
          businessCategory: data.businessCategory || c.businessCategory,
          companyPhone: data.companyPhone || c.phone,
          quotationDate: data.quotationDate || format(new Date(), 'yyyy-MM-dd'),
        });
      }
      setIsLoadingCompany(false);
    }
    if (!data.companyName) {
      loadCompanyInfo();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleAddItem = () => {
    onChange({ ...data, items: [...data.items, createEmptyItem()] });
  };

  const handleRemoveItem = (index: number) => {
    const items = data.items.filter((_, i) => i !== index);
    onChange({ ...data, items });
  };

  const handleItemChange = (index: number, field: keyof QuotationItem, value: string | number) => {
    const items = [...data.items];
    const item = { ...items[index], [field]: value };
    items[index] = calcItem(item, data.autoTax);
    onChange({ ...data, items });
  };

  const handleAutoTaxChange = (checked: boolean) => {
    const items = data.items.map((item) => calcItem(item, checked));
    onChange({ ...data, autoTax: checked, items });
  };

  // 합계 계산
  const totalSupply = data.items.reduce((sum, item) => sum + item.supplyAmount, 0);
  const totalTax = data.items.reduce((sum, item) => sum + item.tax, 0);
  const grandTotal = totalSupply + totalTax;

  return (
    <div className="space-y-6">
      {/* 1. 수신 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">수신 정보</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>수신/고객명 <span className="text-red-500">*</span></Label>
            <Input
              placeholder="고객명을 입력해주세요"
              value={data.recipientName}
              onChange={(e) => onChange({ ...data, recipientName: e.target.value })}
            />
          </div>
          <div className="space-y-2">
            <Label>견적일자 <span className="text-red-500">*</span></Label>
            <DatePicker
              value={data.quotationDate}
              onChange={(date) => onChange({ ...data, quotationDate: date })}
            />
          </div>
        </div>
      </div>

      {/* 2. 공급자 정보 (회사 자동입력) */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">
          공급자
          {isLoadingCompany && <span className="text-sm text-gray-400 ml-2">불러오는 중...</span>}
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label>사업자번호</Label>
            <Input value={data.businessNumber} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>상호</Label>
            <Input value={data.companyName} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>대표자</Label>
            <Input value={data.representativeName} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>소재지</Label>
            <Input value={data.companyAddress} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>업태</Label>
            <Input
              value={data.businessType}
              onChange={(e) => onChange({ ...data, businessType: e.target.value })}
            />
          </div>
          <div className="space-y-2">
            <Label>업종</Label>
            <Input
              value={data.businessCategory}
              onChange={(e) => onChange({ ...data, businessCategory: e.target.value })}
            />
          </div>
          <div className="space-y-2">
            <Label>연락처</Label>
            <Input value={data.companyPhone} disabled className="bg-gray-50" />
          </div>
          <div className="space-y-2">
            <Label>계좌번호</Label>
            <Input
              placeholder="(은행명) 계좌번호"
              value={data.accountNumber}
              onChange={(e) => onChange({ ...data, accountNumber: e.target.value })}
            />
          </div>
        </div>
      </div>

      {/* 3. 견적 품목 */}
      <div className="bg-white rounded-lg border p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold">견적 품목</h3>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-1.5">
              <Checkbox
                id="autoTax"
                checked={data.autoTax}
                onCheckedChange={(checked) => handleAutoTaxChange(checked === true)}
              />
              <Label htmlFor="autoTax" className="text-sm cursor-pointer">부가세 자동(10%)</Label>
            </div>
            <Button type="button" variant="outline" size="sm" onClick={handleAddItem}>
              <Plus className="h-4 w-4 mr-1" />
              품목 추가
            </Button>
          </div>
        </div>

        {data.items.length === 0 ? (
          <div className="text-center text-sm text-gray-400 py-8 border rounded">
            항목을 추가해주세요
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm border">
              <thead>
                <tr className="bg-gray-50">
                  <th className="border px-2 py-2 w-10">#</th>
                  <th className="border px-2 py-2">품명</th>
                  <th className="border px-2 py-2">규격</th>
                  <th className="border px-2 py-2 w-20">수량</th>
                  <th className="border px-2 py-2 w-28">단가</th>
                  <th className="border px-2 py-2 w-28">공급가액</th>
                  <th className="border px-2 py-2 w-24">세액</th>
                  <th className="border px-2 py-2">비고</th>
                  <th className="border px-2 py-2 w-10"></th>
                </tr>
              </thead>
              <tbody>
                {data.items.map((item, index) => (
                  <tr key={item.id}>
                    <td className="border px-2 py-1 text-center">{index + 1}</td>
                    <td className="border px-1 py-1">
                      <Input
                        value={item.name}
                        onChange={(e) => handleItemChange(index, 'name', e.target.value)}
                        className="h-8 border-0"
                        placeholder="품명"
                      />
                    </td>
                    <td className="border px-1 py-1">
                      <Input
                        value={item.specification}
                        onChange={(e) => handleItemChange(index, 'specification', e.target.value)}
                        className="h-8 border-0"
                        placeholder="규격"
                      />
                    </td>
                    <td className="border px-1 py-1">
                      <Input
                        type="number"
                        value={item.quantity || ''}
                        onChange={(e) => handleItemChange(index, 'quantity', Number(e.target.value))}
                        className="h-8 border-0 text-right"
                      />
                    </td>
                    <td className="border px-1 py-1">
                      <CurrencyInput
                        value={item.unitPrice}
                        onChange={(value) => handleItemChange(index, 'unitPrice', value ?? 0)}
                        className="h-8 border-0"
                      />
                    </td>
                    <td className="border px-2 py-1 text-right bg-gray-50">
                      {formatNumber(item.supplyAmount)}
                    </td>
                    <td className="border px-2 py-1 text-right bg-gray-50">
                      {formatNumber(item.tax)}
                    </td>
                    <td className="border px-1 py-1">
                      <Input
                        value={item.note}
                        onChange={(e) => handleItemChange(index, 'note', e.target.value)}
                        className="h-8 border-0"
                      />
                    </td>
                    <td className="border px-1 py-1 text-center">
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => handleRemoveItem(index)}
                        className="h-7 w-7 p-0 text-red-500 hover:text-red-700"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
              <tfoot>
                <tr className="bg-gray-50 font-semibold">
                  <td colSpan={5} className="border px-2 py-2 text-right">합 계</td>
                  <td className="border px-2 py-2 text-right">{formatNumber(totalSupply)}</td>
                  <td className="border px-2 py-2 text-right">{formatNumber(totalTax)}</td>
                  <td colSpan={2} className="border"></td>
                </tr>
                <tr className="bg-blue-50 font-semibold">
                  <td colSpan={5} className="border px-2 py-2 text-right">견적금액 (공급가액 + 세액)</td>
                  <td colSpan={4} className="border px-2 py-2 text-right">{formatNumber(grandTotal)}원</td>
                </tr>
              </tfoot>
            </table>
          </div>
        )}
      </div>

      {/* 4. 특이사항 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">특이사항</h3>
        <Textarea
          placeholder="예: *부가세액 별도* 특이사항을 적어주세요"
          value={data.specialNotes}
          onChange={(e) => onChange({ ...data, specialNotes: e.target.value })}
          className="min-h-[80px]"
        />
      </div>
    </div>
  );
}
