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 { Input } from './ui/input';
import { Label } from './ui/label';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import { 
  Building,
  Network,
  Users,
  Plus,
  Edit,
  Trash2,
  Eye,
  User
} from 'lucide-react';

interface Department {
  id: string;
  code: string;
  name: string;
  manager: string;
  parentDepartment: string | null;
  employeeCount: number;
  phone: string;
  description: string;
  status: '활성' | '비활성';
}

export function DepartmentManagement() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('전체');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingDepartment, setEditingDepartment] = useState<Department | null>(null);

  // 모의 데이터
  const departments: Department[] = [
    {
      id: 'DEPT001',
      code: 'PRD',
      name: '생산팀',
      manager: '최동훈',
      parentDepartment: '제조본부',
      employeeCount: 35,
      phone: '02-1234-5601',
      description: '제품 생산 및 공정 관리',
      status: '활성'
    },
    {
      id: 'DEPT002',
      code: 'QA',
      name: '품질팀',
      manager: '이영희',
      parentDepartment: '제조본부',
      employeeCount: 18,
      phone: '02-1234-5602',
      description: '품질 검사 및 관리',
      status: '활성'
    },
    {
      id: 'DEPT003',
      code: 'MAT',
      name: '자재팀',
      manager: '박민수',
      parentDepartment: '제조본부',
      employeeCount: 12,
      phone: '02-1234-5603',
      description: '자재 구매 및 재고 관리',
      status: '활성'
    },
    {
      id: 'DEPT004',
      code: 'SLS',
      name: '영업팀',
      manager: '정수진',
      parentDepartment: '영업본부',
      employeeCount: 22,
      phone: '02-1234-5604',
      description: '영업 및 고객 관리',
      status: '활성'
    },
    {
      id: 'DEPT005',
      code: 'FIN',
      name: '재무팀',
      manager: '강민호',
      parentDepartment: '경영지원본부',
      employeeCount: 8,
      phone: '02-1234-5605',
      description: '재무 및 회계 관리',
      status: '활성'
    },
    {
      id: 'DEPT006',
      code: 'HR',
      name: '인사팀',
      manager: '송지은',
      parentDepartment: '경영지원본부',
      employeeCount: 6,
      phone: '02-1234-5606',
      description: '인사 및 노무 관리',
      status: '활성'
    },
    {
      id: 'DEPT007',
      code: 'RND',
      name: '개발팀',
      manager: '이현우',
      parentDepartment: '연구개발본부',
      employeeCount: 15,
      phone: '02-1234-5607',
      description: '제품 연구 및 개발',
      status: '활성'
    },
    {
      id: 'DEPT008',
      code: 'OLD',
      name: '구매팀',
      manager: '-',
      parentDepartment: null,
      employeeCount: 0,
      phone: '-',
      description: '자재팀으로 통합됨',
      status: '비활성'
    },
  ];

  const filteredDepartments = departments.filter(dept => {
    const matchesSearch = dept.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         dept.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         dept.manager.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === '전체' || dept.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const totalDepts = departments.length;
  const activeDepts = departments.filter(d => d.status === '활성').length;
  const totalEmployees = departments.reduce((sum, dept) => sum + dept.employeeCount, 0);
  const avgEmployees = Math.round(totalEmployees / activeDepts);

  const handleEdit = (department: Department) => {
    setEditingDepartment(department);
    setIsDialogOpen(true);
  };

  const handleAddNew = () => {
    setEditingDepartment(null);
    setIsDialogOpen(true);
  };

  const handleDelete = (id: string) => {
    if (confirm('정말 삭제하시겠습니까?')) {
      console.log('삭제:', id);
    }
  };

  const columns: Column<Department>[] = [
    {
      key: 'code',
      label: '부서 코드',
      render: (value) => <Badge variant="outline">{value as string}</Badge>
    },
    {
      key: 'name',
      label: '부서명'
    },
    {
      key: 'parentDepartment',
      label: '상위 부서',
      render: (value) => (value as string | null) || '-'
    },
    {
      key: 'manager',
      label: '부서장'
    },
    {
      key: 'employeeCount',
      label: '인원',
      render: (value) => `${value}명`
    },
    {
      key: 'phone',
      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={Building}
        stats={[
          {
            label: "전체 부서",
            value: `${totalDepts}개`,
            icon: Network,
            iconColor: "text-blue-600",
            description: "등록된 부서"
          },
          {
            label: "활성 부서",
            value: `${activeDepts}개`,
            icon: Building,
            iconColor: "text-green-600",
            description: `${((activeDepts / totalDepts) * 100).toFixed(1)}%`
          },
          {
            label: "전체 인원",
            value: `${totalEmployees}명`,
            icon: Users,
            iconColor: "text-purple-600",
            description: "소속 인원"
          },
          {
            label: "평균 인원",
            value: `${avgEmployees}명`,
            icon: User,
            iconColor: "text-orange-600",
            description: "부서당 평균"
          }
        ]}
        actions={
          <Button onClick={handleAddNew}>
            <Plus className="w-4 h-4 mr-2" />
            부서 등록
          </Button>
        }
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="부서명, 코드, 부서장 검색..."
        extraActions={
          <Select value={selectedStatus} onValueChange={setSelectedStatus}>
            <SelectTrigger className="w-[150px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="전체">전체</SelectItem>
              <SelectItem value="활성">활성</SelectItem>
              <SelectItem value="비활성">비활성</SelectItem>
            </SelectContent>
          </Select>
        }
        data={filteredDepartments}
        keyField="id"
        columns={columns}
        renderMobileCard={(dept) => ({
          title: dept.name,
          subtitle: `${dept.code} | ${dept.manager}`,
          badge: {
            label: dept.status,
            variant: dept.status === '활성' ? 'default' : 'secondary'
          },
          fields: [
            {
              label: "상위 부서",
              value: dept.parentDepartment || '-'
            },
            {
              label: "인원",
              value: `${dept.employeeCount}명`
            },
            {
              label: "전화번호",
              value: dept.phone
            },
            {
              label: "설명",
              value: dept.description
            }
          ],
          actions: [
            {
              label: "수정",
              icon: Edit,
              onClick: () => handleEdit(dept)
            },
            {
              label: "삭제",
              icon: Trash2,
              onClick: () => handleDelete(dept.id),
              variant: "destructive"
            }
          ]
        })}
        emptyIcon={Building}
        emptyTitle="등록된 부서가 없습니다"
        emptyDescription="새 부서를 등록해주세요"
      />

      {/* Dialog는 기존 코드 유지 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {editingDepartment ? '부서 수정' : '부서 등록'}
            </DialogTitle>
            <DialogDescription>
              {editingDepartment ? '부서 정보를 수정합니다.' : '새로운 부서를 등록합니다.'}
            </DialogDescription>
          </DialogHeader>
          <div className="py-4 px-6">
            <p className="text-sm text-muted-foreground">부서 등록/수정 기능은 별도로 구현됩니다.</p>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}