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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import {
  ShoppingCart,
  Plus,
  Edit,
  Eye,
  Calendar,
  Building2,
  CheckCircle,
  Clock,
  AlertCircle,
  X,
  FileText,
  User,
  Phone,
  Mail
} from "lucide-react";

interface PurchaseOrderItem {
  code: string;
  name: string;
  spec: string;
  unit: string;
  quantity: number;
  unitPrice: number;
  amount: number;
}

interface PurchaseOrder {
  id: string;
  orderDate: string;
  supplier: string;
  supplierCode: string;
  requiredDate: string;
  status: "승인대기" | "발주중" | "입고완료" | "취소";
  totalAmount: number;
  vat: number;
  totalWithVat: number;
  buyer: string;
  buyerContact?: string;
  buyerMobile?: string;
  buyerEmail?: string;
  paymentTerms: string;
  items: PurchaseOrderItem[];
  note: string;
  approvalStatus: string;
  receivedQuantity: number;
}

// 거래처 인터페이스 (SupplierManagement와 동기화)
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 PurchaseOrderManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("전체");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingOrder, setEditingOrder] = useState<PurchaseOrder | null>(null);
  
  // 폼 상태
  const [formData, setFormData] = useState({
    supplier: "",
    supplierCode: "",
    orderDate: new Date().toISOString().split('T')[0],
    requiredDate: "",
    buyer: "",
    buyerContact: "",
    buyerMobile: "",
    buyerEmail: "",
    paymentTerms: "월말결제",
    note: ""
  });

  // 샘플 거래처 데이터 (실제로는 DataContext에서 가져와야 함)
  const suppliers: 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: '02-3456-7890',
      mobile: '010-3456-7890',
      email: 'motor@company.com',
      address: '인천시 남동구 공단로 456',
      mainProducts: '자동 모터, 구동장치',
      rating: 'S',
      status: '거래중',
      paymentTerms: '익월10일',
      creditLimit: 80000000,
      currentDebt: 9350000,
      manager: '김철수',
      totalPurchase: 280000000,
      lastOrderDate: '2025-03-15',
      note: '신뢰할 수 있는 모터 공급처'
    }
  ];

  // 발주처 선택 시 담당자 정보 자동 입력
  const handleSupplierChange = (supplierName: string) => {
    const supplier = suppliers.find(s => s.name === supplierName);
    if (supplier) {
      setFormData({
        ...formData,
        supplier: supplier.name,
        supplierCode: supplier.code,
        buyer: supplier.manager,
        buyerContact: supplier.contact,
        buyerMobile: supplier.mobile,
        buyerEmail: supplier.email,
        paymentTerms: supplier.paymentTerms
      });
    }
  };

  // 다이얼로그 열기
  const handleOpenDialog = (order?: PurchaseOrder) => {
    if (order) {
      setEditingOrder(order);
      setFormData({
        supplier: order.supplier,
        supplierCode: order.supplierCode,
        orderDate: order.orderDate,
        requiredDate: order.requiredDate,
        buyer: order.buyer,
        buyerContact: order.buyerContact || "",
        buyerMobile: order.buyerMobile || "",
        buyerEmail: order.buyerEmail || "",
        paymentTerms: order.paymentTerms,
        note: order.note
      });
    } else {
      setEditingOrder(null);
      setFormData({
        supplier: "",
        supplierCode: "",
        orderDate: new Date().toISOString().split('T')[0],
        requiredDate: "",
        buyer: "",
        buyerContact: "",
        buyerMobile: "",
        buyerEmail: "",
        paymentTerms: "월말결제",
        note: ""
      });
    }
    setIsDialogOpen(true);
  };

  // 폼 제출
  const handleSubmit = () => {
    // 실제로는 DataContext의 addPurchaseOrder 또는 updatePurchaseOrder 호출
    console.log("발주 저장:", formData);
    setIsDialogOpen(false);
  };

  const purchaseOrders: PurchaseOrder[] = [
    {
      id: "PO-2025-001",
      orderDate: "2025-03-10",
      supplier: "(주)알루미늄공업",
      supplierCode: "S001",
      requiredDate: "2025-03-20",
      status: "입고완료",
      totalAmount: 12500000,
      vat: 1250000,
      totalWithVat: 13750000,
      buyer: "박민수",
      buyerContact: "010-1234-5678",
      buyerMobile: "010-1234-5678",
      buyerEmail: "minsu.park@example.com",
      paymentTerms: "월말결제",
      items: [
        { code: "MAT-001", name: "알루미늄 프로파일", spec: "6063-T5", unit: "M", quantity: 500, unitPrice: 25000, amount: 12500000 }
      ],
      note: "긴급 발주",
      approvalStatus: "승인",
      receivedQuantity: 500
    },
    {
      id: "PO-2025-002",
      orderDate: "2025-03-12",
      supplier: "대한패브릭",
      supplierCode: "S002",
      requiredDate: "2025-03-22",
      status: "발주중",
      totalAmount: 7000000,
      vat: 700000,
      totalWithVat: 7700000,
      buyer: "박민수",
      buyerContact: "010-1234-5678",
      buyerMobile: "010-1234-5678",
      buyerEmail: "minsu.park@example.com",
      paymentTerms: "월말결제",
      items: [
        { code: "MAT-002", name: "패브릭 원단", spec: "폴리에스터 100%", unit: "YD", quantity: 200, unitPrice: 35000, amount: 7000000 }
      ],
      note: "",
      approvalStatus: "승인",
      receivedQuantity: 0
    },
    {
      id: "PO-2025-003",
      orderDate: "2025-03-15",
      supplier: "모터산업",
      supplierCode: "S003",
      requiredDate: "2025-03-25",
      status: "입고완료",
      totalAmount: 8500000,
      vat: 850000,
      totalWithVat: 9350000,
      buyer: "김철수",
      buyerContact: "010-8765-4321",
      buyerMobile: "010-8765-4321",
      buyerEmail: "chelseo.kim@example.com",
      paymentTerms: "익월10일",
      items: [
        { code: "MAT-003", name: "자동 모터", spec: "24V DC", unit: "EA", quantity: 100, unitPrice: 85000, amount: 8500000 }
      ],
      note: "",
      approvalStatus: "승인",
      receivedQuantity: 100
    },
    {
      id: "PO-2025-004",
      orderDate: "2025-03-18",
      supplier: "볼트너트",
      supplierCode: "S004",
      requiredDate: "2025-03-28",
      status: "승인대기",
      totalAmount: 5000000,
      vat: 500000,
      totalWithVat: 5500000,
      buyer: "박민수",
      buyerContact: "010-1234-5678",
      buyerMobile: "010-1234-5678",
      buyerEmail: "minsu.park@example.com",
      paymentTerms: "월말결제",
      items: [
        { code: "MAT-004", name: "볼트/너트 세트", spec: "M8", unit: "SET", quantity: 1000, unitPrice: 5000, amount: 5000000 }
      ],
      note: "",
      approvalStatus: "대기",
      receivedQuantity: 0
    },
    {
      id: "PO-2025-005",
      orderDate: "2025-03-22",
      supplier: "철강유통",
      supplierCode: "S005",
      requiredDate: "2025-04-01",
      status: "발주중",
      totalAmount: 13500000,
      vat: 1350000,
      totalWithVat: 14850000,
      buyer: "김철수",
      buyerContact: "010-8765-4321",
      buyerMobile: "010-8765-4321",
      buyerEmail: "chelseo.kim@example.com",
      paymentTerms: "월말결제",
      items: [
        { code: "MAT-005", name: "철판 1.2T", spec: "SPCC", unit: "KG", quantity: 300, unitPrice: 45000, amount: 13500000 }
      ],
      note: "",
      approvalStatus: "승인",
      receivedQuantity: 0
    }
  ];

  const filteredOrders = purchaseOrders.filter(order => {
    const matchesSearch = order.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         order.supplier.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = selectedStatus === "전체" || order.status === selectedStatus;
    return matchesSearch && matchesStatus;
  });

  const getStatusBadgeVariant = (status: string): "default" | "secondary" | "outline" | "destructive" => {
    switch (status) {
      case "입고완료": return "default";
      case "발주중": return "secondary";
      case "승인대기": return "outline";
      case "취소": return "destructive";
      default: return "outline";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "입고완료": return <CheckCircle className="h-3 w-3 mr-1" />;
      case "발주중": return <Clock className="h-3 w-3 mr-1" />;
      case "승인대기": return <AlertCircle className="h-3 w-3 mr-1" />;
      case "취소": return <X className="h-3 w-3 mr-1" />;
      default: return null;
    }
  };

  const stats = [
    {
      label: "전체 발주",
      value: purchaseOrders.length,
      icon: ShoppingCart,
      iconColor: "text-blue-600"
    },
    {
      label: "승인대기",
      value: purchaseOrders.filter(o => o.status === "승인대기").length,
      icon: AlertCircle,
      iconColor: "text-orange-600"
    },
    {
      label: "발주중",
      value: purchaseOrders.filter(o => o.status === "발주중").length,
      icon: Clock,
      iconColor: "text-blue-600"
    },
    {
      label: "입고완료",
      value: purchaseOrders.filter(o => o.status === "입고완료").length,
      icon: CheckCircle,
      iconColor: "text-green-600"
    },
    {
      label: "총 발주액",
      value: `${(purchaseOrders.reduce((sum, o) => sum + o.totalWithVat, 0) / 100000000).toFixed(1)}억원`,
      icon: FileText,
      iconColor: "text-purple-600"
    }
  ];

  const columns: Column<PurchaseOrder>[] = [
    {
      key: "id",
      label: "발주번호",
      width: "130px",
      render: (value) => <span className="font-mono">{value}</span>
    },
    {
      key: "orderDate",
      label: "발주일자",
      render: (value) => (
        <div className="flex items-center gap-2">
          <Calendar className="h-4 w-4 text-muted-foreground" />
          {value}
        </div>
      )
    },
    {
      key: "supplier",
      label: "공급처",
      render: (value) => (
        <div className="flex items-center gap-2">
          <Building2 className="h-4 w-4 text-muted-foreground" />
          {value}
        </div>
      )
    },
    {
      key: "requiredDate",
      label: "납기요청일"
    },
    {
      key: "totalWithVat",
      label: "발주금액",
      render: (value) => `${(value as number).toLocaleString()}원`
    },
    {
      key: "buyer",
      label: "담당자"
    },
    {
      key: "status",
      label: "상태",
      render: (value, row) => (
        <Badge variant={getStatusBadgeVariant(value as string)}>
          {getStatusIcon(value as string)}
          {value}
        </Badge>
      )
    },
    {
      key: "actions",
      label: "관리",
      render: (value, row) => (
        <div className="flex gap-2">
          <Button variant="ghost" size="sm">
            <Eye className="h-4 w-4" />
          </Button>
          {row.status === "승인대기" && (
            <Button variant="ghost" size="sm">
              <Edit className="h-4 w-4" />
            </Button>
          )}
        </div>
      )
    }
  ];

  const extraActions = (
    <Select value={selectedStatus} onValueChange={setSelectedStatus}>
      <SelectTrigger className="w-[150px]">
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {["전체", "승인대기", "발주중", "입고완료", "취소"].map((status) => (
          <SelectItem key={status} value={status}>
            {status}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );

  return (
    <>
      <ListPageTemplate
        title="발주관리"
        description="자재 및 부품 발주를 관리합니다"
        icon={ShoppingCart}
        actions={
          <Button onClick={() => handleOpenDialog()}>
            <Plus className="h-4 w-4 mr-2" />
            발주 등록
          </Button>
        }
        stats={stats}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="발주번호, 공급처명으로 검색..."
        filterButton={false}
        extraActions={extraActions}
        data={filteredOrders}
        keyField="id"
        columns={columns}
        renderMobileCard={(order) => ({
          title: order.id,
          subtitle: order.supplier,
          badge: {
            label: order.status,
            variant: getStatusBadgeVariant(order.status)
          },
          fields: [
            {
              label: "발주일자",
              value: order.orderDate
            },
            {
              label: "납기요청일",
              value: order.requiredDate
            },
            {
              label: "발주금액",
              value: `${order.totalWithVat.toLocaleString()}원`
            },
            {
              label: "담당자",
              value: order.buyer
            }
          ],
          actions: [
            {
              label: "보기",
              onClick: () => {},
              icon: Eye,
              variant: "outline" as const
            },
            ...(order.status === "승인대기" ? [{
              label: "수정",
              onClick: () => handleOpenDialog(order),
              icon: Edit,
              variant: "outline" as const
            }] : [])
          ]
        })}
        emptyIcon={ShoppingCart}
        emptyTitle="등록된 발주가 없습니다"
        emptyDescription="새로운 발주를 등록해주세요"
      />

      {/* 발주 등록/수정 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingOrder ? "발주 수정" : "발주 등록"}
            </DialogTitle>
            <DialogDescription>
              발주 정보를 입력해주세요
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6 py-4">
            {/* 기본 정보 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>발주처 *</Label>
                <Select 
                  value={formData.supplier} 
                  onValueChange={handleSupplierChange}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="발주처 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {suppliers
                      .filter(s => s.status === '거래중')
                      .map((supplier) => (
                        <SelectItem key={supplier.id} value={supplier.name}>
                          <div className="flex items-center gap-2">
                            <Building2 className="h-4 w-4" />
                            {supplier.name} ({supplier.code})
                          </div>
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                {formData.supplierCode && (
                  <p className="text-xs text-muted-foreground">
                    거래처 코드: {formData.supplierCode}
                  </p>
                )}
              </div>

              <div className="space-y-2">
                <Label>결제조건</Label>
                <Select 
                  value={formData.paymentTerms}
                  onValueChange={(value) => setFormData({...formData, paymentTerms: value})}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="월말결제">월말결제</SelectItem>
                    <SelectItem value="익월10일">익월10일</SelectItem>
                    <SelectItem value="익월말">익월말</SelectItem>
                    <SelectItem value="현금">현금</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label>발주일자 *</Label>
                <Input
                  type="date"
                  value={formData.orderDate}
                  onChange={(e) => setFormData({...formData, orderDate: e.target.value})}
                />
              </div>

              <div className="space-y-2">
                <Label>납기요청일 *</Label>
                <Input
                  type="date"
                  value={formData.requiredDate}
                  onChange={(e) => setFormData({...formData, requiredDate: e.target.value})}
                />
              </div>
            </div>

            {/* 발주 담당자 정보 */}
            <div className="border rounded-lg p-4 bg-blue-50 space-y-4">
              <div className="flex items-center gap-2 mb-2">
                <User className="h-4 w-4 text-blue-600" />
                <h3 className="font-medium text-blue-900">발주 담당자 정보</h3>
                <Badge variant="secondary" className="text-xs">
                  거래처 정보에서 자동 입력 / 수정 가능
                </Badge>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="flex items-center gap-2">
                    <User className="h-3.5 w-3.5" />
                    담당자명
                  </Label>
                  <Input
                    value={formData.buyer}
                    onChange={(e) => setFormData({...formData, buyer: e.target.value})}
                    placeholder="담당자명 입력"
                  />
                </div>

                <div className="space-y-2">
                  <Label className="flex items-center gap-2">
                    <Phone className="h-3.5 w-3.5" />
                    연락처
                  </Label>
                  <Input
                    value={formData.buyerContact}
                    onChange={(e) => setFormData({...formData, buyerContact: e.target.value})}
                    placeholder="예: 02-1234-5678"
                  />
                </div>

                <div className="space-y-2">
                  <Label className="flex items-center gap-2">
                    <Phone className="h-3.5 w-3.5" />
                    휴대폰
                  </Label>
                  <Input
                    value={formData.buyerMobile}
                    onChange={(e) => setFormData({...formData, buyerMobile: e.target.value})}
                    placeholder="예: 010-1234-5678"
                  />
                </div>

                <div className="space-y-2">
                  <Label className="flex items-center gap-2">
                    <Mail className="h-3.5 w-3.5" />
                    이메일
                  </Label>
                  <Input
                    value={formData.buyerEmail}
                    onChange={(e) => setFormData({...formData, buyerEmail: e.target.value})}
                    placeholder="예: contact@example.com"
                  />
                </div>
              </div>
            </div>

            {/* 비고 */}
            <div className="space-y-2">
              <Label>비고</Label>
              <Textarea
                value={formData.note}
                onChange={(e) => setFormData({...formData, note: e.target.value})}
                placeholder="특이사항을 입력하세요"
                rows={3}
              />
            </div>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button 
              variant="outline" 
              onClick={() => setIsDialogOpen(false)}
            >
              취소
            </Button>
            <Button 
              onClick={handleSubmit}
              disabled={!formData.supplier || !formData.orderDate || !formData.requiredDate}
            >
              {editingOrder ? "수정" : "등록"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}