import { useState } from 'react';
import { ListPageTemplate } from './templates/ListPageTemplate';
import { Column } from './organisms/DataTable';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from './ui/dialog';
import { Label } from './ui/label';
import { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import {
  Building2,
  Plus,
  TrendingUp,
  AlertCircle,
  Star,
  Eye,
  Edit,
  Trash2
} from 'lucide-react';

interface Supplier {
  id: string;
  code: string;
  name: string;
  category: string;
  representative: string;
  businessNo: string;
  contact: string;
  mobile: string;
  email: string;
  address: string;
  mainProducts: string;
  rating: 'S' | 'A' | 'B' | 'C';
  status: '거래중' | '거래중지' | '평가중';
  paymentTerms: string;
  creditLimit: number;
  currentDebt: number;
  manager: string;
  totalPurchase: number;
  lastOrderDate: string;
  note?: string;
}

export function SupplierManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState('all');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);

  const [suppliers, setSuppliers] = useState<Supplier[]>([
    {
      id: 'SUP-001',
      code: 'S001',
      name: '(주)알루미늄공업',
      category: '원자재',
      representative: '김대표',
      businessNo: '123-45-67890',
      contact: '02-1234-5678',
      mobile: '010-1234-5678',
      email: 'aluminum@company.com',
      address: '서울시 금천구 가산디지털1로 119',
      mainProducts: '알루미늄 프로파일, 압출재',
      rating: 'A',
      status: '거래중',
      paymentTerms: '월말결제',
      creditLimit: 50000000,
      currentDebt: 13750000,
      manager: '박민수',
      totalPurchase: 125000000,
      lastOrderDate: '2025-03-10',
      note: '주요 알루미늄 공급처'
    },
    {
      id: 'SUP-002',
      code: 'S002',
      name: '대한패브릭',
      category: '원자재',
      representative: '이대표',
      businessNo: '234-56-78901',
      contact: '031-2345-6789',
      mobile: '010-2345-6789',
      email: 'fabric@company.com',
      address: '경기도 시흥시 공단로 123',
      mainProducts: '패브릭 원단, 직물',
      rating: 'A',
      status: '거래중',
      paymentTerms: '월말결제',
      creditLimit: 30000000,
      currentDebt: 7700000,
      manager: '박민수',
      totalPurchase: 85000000,
      lastOrderDate: '2025-03-12',
      note: '패브릭 전문 공급처'
    },
    {
      id: 'SUP-003',
      code: 'S003',
      name: '모터산업',
      category: '부품',
      representative: '박대표',
      businessNo: '345-67-89012',
      contact: '032-3456-7890',
      mobile: '010-3456-7890',
      email: 'motor@company.com',
      address: '인천시 남동구 공단로 456',
      mainProducts: '자동 모터, 제어장치',
      rating: 'B',
      status: '거래중',
      paymentTerms: '익월10일',
      creditLimit: 40000000,
      currentDebt: 9350000,
      manager: '김철수',
      totalPurchase: 95000000,
      lastOrderDate: '2025-03-15',
      note: '모터 전문 제조사'
    }
  ]);

  const filteredSuppliers = suppliers.filter(supplier => {
    const matchesSearch = 
      supplier.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      supplier.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      supplier.representative.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesCategory = filterCategory === 'all' || supplier.category === filterCategory;
    
    return matchesSearch && matchesCategory;
  });

  const totalSuppliers = suppliers.length;
  const activeSuppliers = suppliers.filter(s => s.status === '거래중').length;
  const gradeA = suppliers.filter(s => s.rating === 'A').length;
  const overLimit = suppliers.filter(s => s.currentDebt > s.creditLimit * 0.9).length;

  const handleNew = () => {
    setSelectedSupplier(null);
    setIsDialogOpen(true);
  };

  const handleView = (supplier: Supplier) => {
    setSelectedSupplier(supplier);
    setIsDialogOpen(true);
  };

  const handleEdit = (supplier: Supplier) => {
    setSelectedSupplier(supplier);
    setIsDialogOpen(true);
  };

  const handleDelete = (supplier: Supplier) => {
    if (confirm(`${supplier.name}을(를) 삭제하시겠습니까?`)) {
      setSuppliers(suppliers.filter(s => s.id !== supplier.id));
    }
  };

  const columns: Column<Supplier>[] = [
    { 
      key: 'code', 
      label: '공급처코드' 
    },
    { 
      key: 'name', 
      label: '공급처명' 
    },
    { 
      key: 'category', 
      label: '카테고리',
      render: (value) => <Badge variant="outline">{value as string}</Badge>
    },
    { 
      key: 'representative', 
      label: '대표자' 
    },
    { 
      key: 'contact', 
      label: '연락처' 
    },
    { 
      key: 'rating', 
      label: '등급',
      render: (value) => {
        const rating = value as string;
        const className = 
          rating === 'S' ? 'bg-purple-100 text-purple-700 border-purple-200' :
          rating === 'A' ? 'bg-blue-100 text-blue-700 border-blue-200' :
          rating === 'B' ? 'bg-green-100 text-green-700 border-green-200' :
          'bg-gray-100 text-gray-700 border-gray-200';
        return <Badge className={className}>{rating}</Badge>;
      }
    },
    { 
      key: 'status', 
      label: '상태',
      render: (value) => {
        const status = value as string;
        const variant = status === '거래중' ? 'default' : status === '거래중지' ? 'destructive' : 'secondary';
        return <Badge variant={variant}>{status}</Badge>;
      }
    },
    { 
      key: 'totalPurchase', 
      label: '총 구매액',
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    { 
      key: 'lastOrderDate', 
      label: '최근 발주일'
    },
    {
      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={() => handleView(row)}>
            <Eye className="h-4 w-4" />
          </Button>
          <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)}>
            <Trash2 className="h-4 w-4 text-red-500" />
          </Button>
        </div>
      )
    }
  ];

  return (
    <>
      <ListPageTemplate
        title="공급처 관리"
        description="원자재 및 부품 공급처를 관리합니다"
        icon={Building2}
        stats={[
          {
            label: "전체 공급처",
            value: `${totalSuppliers}개`,
            icon: Building2,
            iconColor: "text-blue-600",
            description: "등록된 공급처"
          },
          {
            label: "거래중",
            value: `${activeSuppliers}개`,
            icon: TrendingUp,
            iconColor: "text-green-600",
            description: `${((activeSuppliers / totalSuppliers) * 100).toFixed(1)}%`
          },
          {
            label: "A등급",
            value: `${gradeA}개`,
            icon: Star,
            iconColor: "text-yellow-600",
            description: "우수 공급처"
          },
          {
            label: "신용한도 초과",
            value: `${overLimit}개`,
            icon: AlertCircle,
            iconColor: "text-red-600",
            description: "주의 필요"
          }
        ]}
        actions={
          <Button onClick={handleNew}>
            <Plus className="w-4 h-4 mr-2" />
            공급처 등록
          </Button>
        }
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="공급처명, 코드, 대표자로 검색..."
        extraActions={
          <Select value={filterCategory} onValueChange={setFilterCategory}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="카테고리" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              <SelectItem value="원자재">원자재</SelectItem>
              <SelectItem value="부품">부품</SelectItem>
              <SelectItem value="완제품">완제품</SelectItem>
              <SelectItem value="기타">기타</SelectItem>
            </SelectContent>
          </Select>
        }
        data={filteredSuppliers}
        keyField="id"
        columns={columns}
        renderMobileCard={(supplier) => ({
          title: supplier.name,
          subtitle: `${supplier.code} | ${supplier.representative}`,
          badge: {
            label: supplier.status,
            variant: supplier.status === '거래중' ? 'default' : 'secondary'
          },
          fields: [
            {
              label: "카테고리",
              value: supplier.category
            },
            {
              label: "등급",
              value: supplier.rating
            },
            {
              label: "연락처",
              value: supplier.contact
            },
            {
              label: "주요제품",
              value: supplier.mainProducts
            },
            {
              label: "총 구매액",
              value: `${supplier.totalPurchase.toLocaleString()}원`
            },
            {
              label: "최근 발주일",
              value: supplier.lastOrderDate
            }
          ],
          actions: [
            {
              label: "상세보기",
              icon: Eye,
              onClick: () => handleView(supplier)
            },
            {
              label: "수정",
              icon: Edit,
              onClick: () => handleEdit(supplier)
            },
            {
              label: "삭제",
              icon: Trash2,
              onClick: () => handleDelete(supplier),
              variant: "destructive"
            }
          ]
        })}
        emptyIcon={Building2}
        emptyTitle="등록된 공급처가 없습니다"
        emptyDescription="첫 공급처를 등록하세요"
      />

      {/* Dialog는 기존 코드 유지 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {selectedSupplier ? '공급처 상세' : '공급처 등록'}
            </DialogTitle>
            <DialogDescription>
              공급처 등록/수정 기능은 별도로 구현됩니다.
            </DialogDescription>
          </DialogHeader>
        </DialogContent>
      </Dialog>
    </>
  );
}