import React, { useState } from 'react';
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from './organisms/DataTable';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Badge } from './ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from './ui/dialog';
import {
  Building2,
  Plus,
  Edit,
  Trash2,
  Users,
  CheckCircle,
  XCircle
} from 'lucide-react';

interface CustomerAccount {
  id: string;
  code: string;
  name: string;
  businessNo: string;
  representative: string;
  phone: string;
  address: string;
  email: string;
  businessType: string;
  businessItem: string;
  registeredDate: string;
  status: '활성' | '비활성';
}

export function CustomerAccountManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<CustomerAccount | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    businessNo: '',
    representative: '',
    phone: '',
    address: '',
    email: '',
    businessType: '',
    businessItem: '',
  });

  // 매출처 데이터
  const [customers, setCustomers] = useState<CustomerAccount[]>([
    {
      id: '1',
      code: 'C-001',
      name: 'ABC건설',
      businessNo: '123-45-67890',
      representative: '홍길동',
      phone: '02-1234-5678',
      address: '서울시 강남구 테헤란로 123',
      email: 'abc@company.com',
      businessType: '건설업',
      businessItem: '건축공사',
      registeredDate: '2024-01-15',
      status: '활성',
    },
    {
      id: '2',
      code: 'C-002',
      name: '삼성전자',
      businessNo: '234-56-78901',
      representative: '김대표',
      phone: '02-2345-6789',
      address: '서울시 서초구 서초대로 456',
      email: 'samsung@company.com',
      businessType: '제조업',
      businessItem: '전자제품',
      registeredDate: '2024-02-20',
      status: '활성',
    },
    {
      id: '3',
      code: 'C-003',
      name: 'LG전자',
      businessNo: '345-67-89012',
      representative: '이사장',
      phone: '02-3456-7890',
      address: '서울시 영등포구 여의대로 789',
      email: 'lg@company.com',
      businessType: '제조업',
      businessItem: '가전제품',
      registeredDate: '2024-03-10',
      status: '활성',
    },
    {
      id: '4',
      code: 'C-004',
      name: '현대건설',
      businessNo: '456-78-90123',
      representative: '박부장',
      phone: '02-4567-8901',
      address: '서울시 종로구 종로 101',
      email: 'hyundai@company.com',
      businessType: '건설업',
      businessItem: '토목공사',
      registeredDate: '2024-04-05',
      status: '비활성',
    },
  ]);

  // 검색 필터링
  const filteredCustomers = customers.filter(customer =>
    customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    customer.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
    customer.representative.toLowerCase().includes(searchTerm.toLowerCase()) ||
    customer.phone.includes(searchTerm)
  );

  // 통계
  const totalCustomers = customers.length;
  const activeCustomers = customers.filter(c => c.status === '활성').length;
  const inactiveCustomers = customers.filter(c => c.status === '비활성').length;

  // 신규 등록 모달 열기
  const handleAddNew = () => {
    setEditingCustomer(null);
    setFormData({
      name: '',
      businessNo: '',
      representative: '',
      phone: '',
      address: '',
      email: '',
      businessType: '',
      businessItem: '',
    });
    setIsModalOpen(true);
  };

  // 수정 모달 열기
  const handleEdit = (customer: CustomerAccount) => {
    setEditingCustomer(customer);
    setFormData({
      name: customer.name,
      businessNo: customer.businessNo,
      representative: customer.representative,
      phone: customer.phone,
      address: customer.address,
      email: customer.email,
      businessType: customer.businessType,
      businessItem: customer.businessItem,
    });
    setIsModalOpen(true);
  };

  // 저장
  const handleSave = () => {
    if (editingCustomer) {
      // 수정
      setCustomers(customers.map(c =>
        c.id === editingCustomer.id
          ? { ...c, ...formData }
          : c
      ));
    } else {
      // 신규 등록
      const newCode = `C-${String(customers.length + 1).padStart(3, '0')}`;
      const newCustomer: CustomerAccount = {
        id: String(customers.length + 1),
        code: newCode,
        ...formData,
        registeredDate: new Date().toISOString().split('T')[0],
        status: '활성',
      };
      setCustomers([...customers, newCustomer]);
    }
    setIsModalOpen(false);
  };

  // 삭제
  const handleDelete = (id: string) => {
    if (confirm('정말 삭제하시겠습니까?')) {
      setCustomers(customers.filter(c => c.id !== id));
    }
  };

  const columns: Column<CustomerAccount>[] = [
    {
      key: 'code',
      label: '코드'
    },
    {
      key: 'name',
      label: '거래처명'
    },
    {
      key: 'businessNo',
      label: '사업자번호'
    },
    {
      key: 'representative',
      label: '대표자'
    },
    {
      key: 'phone',
      label: '전화번호'
    },
    {
      key: 'businessType',
      label: '업태'
    },
    {
      key: 'businessItem',
      label: '업종'
    },
    {
      key: 'status',
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '활성' ? 'default' : 'secondary';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    {
      key: 'actions',
      label: '관리',
      render: (_, row) => (
        <div className="flex justify-end gap-1">
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleEdit(row)}>
            <Edit className="h-4 w-4" />
          </Button>
          <Button size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={() => handleDelete(row.id)}>
            <Trash2 className="h-4 w-4 text-red-500" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <>
      <ListPageTemplate
        title="매출처 목록"
        description="거래처 정보 및 계정을 관리합니다"
        icon={Building2}
        stats={[
          {
            label: "전체 거래처",
            value: `${totalCustomers}개`,
            icon: Users,
            iconColor: "text-blue-600",
            description: "등록된 거래처"
          },
          {
            label: "활성 거래처",
            value: `${activeCustomers}개`,
            icon: CheckCircle,
            iconColor: "text-green-600",
            description: `${((activeCustomers / totalCustomers) * 100).toFixed(1)}%`
          },
          {
            label: "비활성 거래처",
            value: `${inactiveCustomers}개`,
            icon: XCircle,
            iconColor: "text-gray-600",
            description: `${((inactiveCustomers / totalCustomers) * 100).toFixed(1)}%`
          }
        ]}
        actions={
          <Button onClick={handleAddNew}>
            <Plus className="w-4 h-4 mr-2" />
            거래처 등록
          </Button>
        }
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="거래처명, 코드, 대표자, 전화번호 검색..."
        data={filteredCustomers}
        keyField="id"
        columns={columns}
        renderMobileCard={(customer) => ({
          title: customer.name,
          subtitle: `${customer.code} | ${customer.representative}`,
          badge: {
            label: customer.status,
            variant: customer.status === '활성' ? 'default' : 'secondary'
          },
          fields: [
            {
              label: "사업자번호",
              value: customer.businessNo
            },
            {
              label: "전화번호",
              value: customer.phone
            },
            {
              label: "이메일",
              value: customer.email
            },
            {
              label: "업태/업종",
              value: `${customer.businessType} / ${customer.businessItem}`
            },
            {
              label: "등록일",
              value: customer.registeredDate
            }
          ],
          actions: [
            {
              label: "수정",
              icon: Edit,
              onClick: () => handleEdit(customer)
            },
            {
              label: "삭제",
              icon: Trash2,
              onClick: () => handleDelete(customer.id),
              variant: "destructive"
            }
          ]
        })}
        emptyIcon={Building2}
        emptyTitle="등록된 거래처가 없습니다"
        emptyDescription="새 거래처를 등록해주세요"
      />

      {/* 등록/수정 모달 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editingCustomer ? '거래처 수정' : '거래처 등록'}
            </DialogTitle>
            <DialogDescription>
              거래처 정보를 입력하세요
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-4 py-4 px-6">
            <div className="space-y-2">
              <Label htmlFor="name">거래처명 *</Label>
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder="ABC건설"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="businessNo">사업자번호 *</Label>
              <Input
                id="businessNo"
                value={formData.businessNo}
                onChange={(e) => setFormData({ ...formData, businessNo: e.target.value })}
                placeholder="123-45-67890"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="representative">대표자 *</Label>
              <Input
                id="representative"
                value={formData.representative}
                onChange={(e) => setFormData({ ...formData, representative: e.target.value })}
                placeholder="홍길동"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="phone">전화번호 *</Label>
              <Input
                id="phone"
                value={formData.phone}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                placeholder="02-1234-5678"
              />
            </div>
            <div className="space-y-2 col-span-2">
              <Label htmlFor="address">주소 *</Label>
              <Input
                id="address"
                value={formData.address}
                onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                placeholder="서울시 강남구 테헤란로 123"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">이메일</Label>
              <Input
                id="email"
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                placeholder="abc@company.com"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="businessType">업태</Label>
              <Input
                id="businessType"
                value={formData.businessType}
                onChange={(e) => setFormData({ ...formData, businessType: e.target.value })}
                placeholder="건설업"
              />
            </div>
            <div className="space-y-2 col-span-2">
              <Label htmlFor="businessItem">업종</Label>
              <Input
                id="businessItem"
                value={formData.businessItem}
                onChange={(e) => setFormData({ ...formData, businessItem: e.target.value })}
                placeholder="건축공사"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsModalOpen(false)}>
              취소
            </Button>
            <Button onClick={handleSave}>
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}