import { useState } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Checkbox } from "./ui/checkbox";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { 
  ShoppingCart, 
  Plus,
  Trash2,
  Package,
  Calendar,
  Truck,
  Save,
  X,
  MapPin,
  User,
  Phone
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { ShippingSchedule } from "./contexts/DataContext";

interface ShippingScheduleForm extends Omit<ShippingSchedule, 'id' | 'status' | 'remainingQuantity'> {
  id?: string;
  status?: ShippingSchedule['status'];
  remainingQuantity?: number;
}

export function SalesOrderWithShippingSchedule({ onBack }: { onBack?: () => void }) {
  // 기본 정보
  const [orderNumber, setOrderNumber] = useState("");
  const [customerName, setCustomerName] = useState("");
  const [projectName, setProjectName] = useState("");
  const [orderDate, setOrderDate] = useState(new Date().toISOString().split('T')[0]);
  const [salesPerson, setSalesPerson] = useState("");
  
  // 품목 정보
  const [itemName, setItemName] = useState("");
  const [totalQuantity, setTotalQuantity] = useState<number>(0);
  const [unit, setUnit] = useState("EA");
  const [unitPrice, setUnitPrice] = useState<number>(0);
  
  // 분할 출고 설정
  const [hasMultipleShipping, setHasMultipleShipping] = useState(false);
  const [shippingSchedules, setShippingSchedules] = useState<ShippingScheduleForm[]>([]);
  
  // 비고
  const [note, setNote] = useState("");

  // 자동으로 수주 번호 생성
  const generateOrderNumber = () => {
    const today = new Date();
    const year = today.getFullYear().toString().slice(-2);
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `KD-PR-${year}${month}${day}-${random}`;
  };

  // 분할 출고 계획 추가
  const addShippingSchedule = () => {
    const scheduleNumber = shippingSchedules.length + 1;
    const newSchedule: ShippingScheduleForm = {
      scheduleNumber,
      scheduledDate: "",
      quantity: 0,
      shippingAddress: "",
      receiverName: "",
      receiverPhone: "",
      note: ""
    };
    setShippingSchedules([...shippingSchedules, newSchedule]);
  };

  // 분할 출고 계획 삭제
  const removeShippingSchedule = (index: number) => {
    const updated = shippingSchedules.filter((_, i) => i !== index);
    // 순번 재정렬
    const reordered = updated.map((schedule, i) => ({
      ...schedule,
      scheduleNumber: i + 1
    }));
    setShippingSchedules(reordered);
  };

  // 분할 출고 계획 업데이트
  const updateShippingSchedule = (index: number, field: keyof ShippingScheduleForm, value: any) => {
    const updated = shippingSchedules.map((schedule, i) => 
      i === index ? { ...schedule, [field]: value } : schedule
    );
    setShippingSchedules(updated);
  };

  // 잔량 계산
  const calculateRemainingQuantity = (index: number): number => {
    const currentQuantity = shippingSchedules.slice(0, index + 1)
      .reduce((sum, schedule) => sum + (schedule.quantity || 0), 0);
    return totalQuantity - currentQuantity;
  };

  // 총 출고 예정 수량 계산
  const getTotalScheduledQuantity = (): number => {
    return shippingSchedules.reduce((sum, schedule) => sum + (schedule.quantity || 0), 0);
  };

  // 유효성 검사
  const validateForm = (): boolean => {
    if (!customerName.trim()) {
      toast.error("고객명을 입력해주세요.");
      return false;
    }
    if (!projectName.trim()) {
      toast.error("프로젝트명을 입력해주세요.");
      return false;
    }
    if (!itemName.trim()) {
      toast.error("품목명을 입력해주세요.");
      return false;
    }
    if (totalQuantity <= 0) {
      toast.error("총 수량을 입력해주세요.");
      return false;
    }
    if (unitPrice <= 0) {
      toast.error("단가를 입력해주세요.");
      return false;
    }

    if (hasMultipleShipping) {
      if (shippingSchedules.length === 0) {
        toast.error("분할 출고 계획을 추가해주세요.");
        return false;
      }

      for (let i = 0; i < shippingSchedules.length; i++) {
        const schedule = shippingSchedules[i];
        if (!schedule.scheduledDate) {
          toast.error(`${schedule.scheduleNumber}차 출하 예정일을 입력해주세요.`);
          return false;
        }
        if (!schedule.quantity || schedule.quantity <= 0) {
          toast.error(`${schedule.scheduleNumber}차 출하 수량을 입력해주세요.`);
          return false;
        }
        if (!schedule.shippingAddress?.trim()) {
          toast.error(`${schedule.scheduleNumber}차 배송지를 입력해주세요.`);
          return false;
        }
      }

      const totalScheduled = getTotalScheduledQuantity();
      if (totalScheduled !== totalQuantity) {
        toast.error(`출하 계획 총 수량(${totalScheduled})이 주문 수량(${totalQuantity})과 일치하지 않습니다.`);
        return false;
      }
    }

    return true;
  };

  // 저장
  const handleSave = () => {
    if (!validateForm()) {
      return;
    }

    const generatedOrderNumber = orderNumber || generateOrderNumber();
    
    // 분할 출고 계획에 잔량 계산 추가
    const schedulesWithRemaining: ShippingSchedule[] = shippingSchedules.map((schedule, index) => ({
      id: `SS-${Date.now()}-${index}`,
      scheduleNumber: schedule.scheduleNumber,
      scheduledDate: schedule.scheduledDate,
      quantity: schedule.quantity,
      remainingQuantity: calculateRemainingQuantity(index),
      shippingAddress: schedule.shippingAddress,
      receiverName: schedule.receiverName,
      receiverPhone: schedule.receiverPhone,
      status: 'scheduled' as const,
      note: schedule.note
    }));

    const salesOrder = {
      id: `SO-${Date.now()}`,
      orderNumber: generatedOrderNumber,
      customerName,
      projectName,
      orderDate,
      deliveryDate: hasMultipleShipping && shippingSchedules.length > 0
        ? shippingSchedules[shippingSchedules.length - 1].scheduledDate
        : orderDate,
      totalAmount: totalQuantity * unitPrice,
      totalQuantity,
      shippedQuantity: 0,
      remainingQuantity: totalQuantity,
      status: 'confirmed' as const,
      hasMultipleShipping,
      items: [{
        id: `SOI-${Date.now()}`,
        itemName,
        quantity: totalQuantity,
        unitPrice,
        totalPrice: totalQuantity * unitPrice
      }],
      shippingSchedules: hasMultipleShipping ? schedulesWithRemaining : undefined
    };

    console.log("수주 등록:", salesOrder);
    toast.success(`수주가 등록되었습니다. (수주번호: ${generatedOrderNumber})`);

    // 폼 초기화
    resetForm();
  };

  // 폼 초기화
  const resetForm = () => {
    setOrderNumber("");
    setCustomerName("");
    setProjectName("");
    setOrderDate(new Date().toISOString().split('T')[0]);
    setSalesPerson("");
    setItemName("");
    setTotalQuantity(0);
    setUnit("EA");
    setUnitPrice(0);
    setHasMultipleShipping(false);
    setShippingSchedules([]);
    setNote("");
  };

  return (
    <PageLayout>
      <PageHeader
        title="수주 등록"
        description="수주 정보 및 분할 출고 계획 등록"
        icon={ShoppingCart}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => onBack?.()}>
              <X className="h-4 w-4 mr-2" />
              취소
            </Button>
            <Button onClick={handleSave}>
              <Save className="h-4 w-4 mr-2" />
              저장
            </Button>
          </div>
        }
      />

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label>수주 번호 (자동생성)</Label>
              <Input
                value={orderNumber}
                onChange={(e) => setOrderNumber(e.target.value)}
                placeholder="저장 시 자동 생성됩니다"
                disabled
              />
            </div>
            <div>
              <Label>수주 일자 *</Label>
              <Input
                type="date"
                value={orderDate}
                onChange={(e) => setOrderDate(e.target.value)}
              />
            </div>
            <div>
              <Label>고객명 *</Label>
              <Input
                value={customerName}
                onChange={(e) => setCustomerName(e.target.value)}
                placeholder="예: (주)한국건설"
              />
            </div>
            <div>
              <Label>프로젝트명 *</Label>
              <Input
                value={projectName}
                onChange={(e) => setProjectName(e.target.value)}
                placeholder="예: 서울 오피스빌딩"
              />
            </div>
            <div>
              <Label>영업 담당자</Label>
              <Input
                value={salesPerson}
                onChange={(e) => setSalesPerson(e.target.value)}
                placeholder="담당자명"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 품목 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>품목 정보</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="md:col-span-2">
              <Label>품목명 *</Label>
              <Input
                value={itemName}
                onChange={(e) => setItemName(e.target.value)}
                placeholder="예: 셔터 세트"
              />
            </div>
            <div>
              <Label>총 수량 *</Label>
              <Input
                type="number"
                value={totalQuantity || ""}
                onChange={(e) => setTotalQuantity(Number(e.target.value))}
                min="0"
                placeholder="0"
              />
            </div>
            <div>
              <Label>단위</Label>
              <Select value={unit} onValueChange={setUnit}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="EA">EA</SelectItem>
                  <SelectItem value="SET">SET</SelectItem>
                  <SelectItem value="M">M</SelectItem>
                  <SelectItem value="KG">KG</SelectItem>
                  <SelectItem value="BOX">BOX</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>단가 *</Label>
              <Input
                type="number"
                value={unitPrice || ""}
                onChange={(e) => setUnitPrice(Number(e.target.value))}
                min="0"
                placeholder="0"
              />
            </div>
            <div>
              <Label>총 금액</Label>
              <Input
                value={(totalQuantity * unitPrice).toLocaleString() + "원"}
                disabled
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 분할 출고 설정 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>분할 출고 설정</CardTitle>
              <p className="text-sm text-muted-foreground mt-1">
                여러 차례에 걸쳐 출하가 필요한 경우 체크하세요
              </p>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="hasMultipleShipping"
                checked={hasMultipleShipping}
                onCheckedChange={(checked) => {
                  setHasMultipleShipping(checked as boolean);
                  if (!checked) {
                    setShippingSchedules([]);
                  }
                }}
              />
              <Label htmlFor="hasMultipleShipping" className="cursor-pointer">
                분할 출고 사용
              </Label>
            </div>
          </div>
        </CardHeader>
        {hasMultipleShipping && (
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="text-sm">
                <span className="text-muted-foreground">총 주문 수량: </span>
                <span className="font-medium">{totalQuantity.toLocaleString()} {unit}</span>
                <span className="mx-2">|</span>
                <span className="text-muted-foreground">출하 계획 수량: </span>
                <span className={`font-medium ${getTotalScheduledQuantity() === totalQuantity ? 'text-green-600' : 'text-red-600'}`}>
                  {getTotalScheduledQuantity().toLocaleString()} {unit}
                </span>
              </div>
              <Button size="sm" onClick={addShippingSchedule}>
                <Plus className="h-4 w-4 mr-2" />
                출하 계획 추가
              </Button>
            </div>

            {shippingSchedules.length > 0 && (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-16">순번</TableHead>
                      <TableHead className="w-32">출하 예정일 *</TableHead>
                      <TableHead className="w-28">출하 수량 *</TableHead>
                      <TableHead className="w-28">출하 후 잔량</TableHead>
                      <TableHead>배송지 *</TableHead>
                      <TableHead className="w-28">수령인</TableHead>
                      <TableHead className="w-32">연락처</TableHead>
                      <TableHead>특이사항</TableHead>
                      <TableHead className="w-16"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {shippingSchedules.map((schedule, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          <Badge variant="outline">{schedule.scheduleNumber}차</Badge>
                        </TableCell>
                        <TableCell>
                          <Input
                            type="date"
                            value={schedule.scheduledDate}
                            onChange={(e) => updateShippingSchedule(index, 'scheduledDate', e.target.value)}
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            value={schedule.quantity || ""}
                            onChange={(e) => updateShippingSchedule(index, 'quantity', Number(e.target.value))}
                            min="0"
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <span className="text-sm font-medium">
                            {calculateRemainingQuantity(index).toLocaleString()} {unit}
                          </span>
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.shippingAddress || ""}
                            onChange={(e) => updateShippingSchedule(index, 'shippingAddress', e.target.value)}
                            placeholder="배송 주소"
                            className="w-full min-w-[200px]"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.receiverName || ""}
                            onChange={(e) => updateShippingSchedule(index, 'receiverName', e.target.value)}
                            placeholder="수령인"
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.receiverPhone || ""}
                            onChange={(e) => updateShippingSchedule(index, 'receiverPhone', e.target.value)}
                            placeholder="010-0000-0000"
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.note || ""}
                            onChange={(e) => updateShippingSchedule(index, 'note', e.target.value)}
                            placeholder="특이사항"
                            className="w-full min-w-[150px]"
                          />
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeShippingSchedule(index)}
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}

            {shippingSchedules.length === 0 && (
              <div className="text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg">
                <Truck className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>출하 계획을 추가해주세요</p>
              </div>
            )}
          </CardContent>
        )}
      </Card>

      {/* 비고 */}
      <Card>
        <CardHeader>
          <CardTitle>비고</CardTitle>
        </CardHeader>
        <CardContent>
          <Textarea
            value={note}
            onChange={(e) => setNote(e.target.value)}
            placeholder="특이사항을 입력하세요"
            rows={4}
          />
        </CardContent>
      </Card>

      {/* 하단 버튼 */}
      <div className="flex justify-end gap-2">
        <Button variant="outline" onClick={() => onBack?.()}>
          <X className="h-4 w-4 mr-2" />
          취소
        </Button>
        <Button onClick={handleSave}>
          <Save className="h-4 w-4 mr-2" />
          저장
        </Button>
      </div>
    </PageLayout>
  );
}