import React, { useState } from "react";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { ArrowLeft, Save, Calendar, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner@2.0.3";

interface WorkOrderWriteProps {
  onBack: () => void;
  onSave?: (data: any) => void;
  productionType?: string;
}

export function WorkOrderWrite({ onBack, onSave, productionType = "" }: WorkOrderWriteProps) {
  const [category, setCategory] = useState<string>(productionType);
  const [formData, setFormData] = useState({
    buyer: "",
    siteName: "",
    productName: "",
    orderDate: new Date().toISOString().split('T')[0],
    requestDate: "",
    quantity: "",
    workPriority: "",
    status: "대기",
    specialNotes: "• 제품은 납기일 하루 전까지 완료되어야 합니다.\n• 현장 설치 일정에 맞춰 출고 준비해 주시기 바랍니다.\n• 품질 검수는 최종 포장 전 반드시 완료해야 합니다."
  });

  const [workProcesses, setWorkProcesses] = useState([
    { process: "재단", content: "", assignee: "김재단", status: "대기" },
    { process: "조립", content: "부품 조립 및 결합", assignee: "이조립", status: "대기" },
    { process: "검수", content: "품질 검사 및 확인", assignee: "박검수", status: "대기" },
    { process: "포장", content: "최종 포장 및 출하 준비", assignee: "최포장", status: "대기" }
  ]);

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleProcessChange = (index: number, field: string, value: string) => {
    const newProcesses = [...workProcesses];
    newProcesses[index] = { ...newProcesses[index], [field]: value };
    setWorkProcesses(newProcesses);
  };

  const addProcess = () => {
    setWorkProcesses([...workProcesses, { process: "", content: "", assignee: "", status: "대기" }]);
  };

  const removeProcess = (index: number) => {
    if (workProcesses.length > 1) {
      setWorkProcesses(workProcesses.filter((_, i) => i !== index));
    }
  };

  const handleSubmit = () => {
    if (!category) {
      toast.error("카테고리를 선택해주세요.");
      return;
    }
    if (!formData.buyer || !formData.siteName || !formData.productName || !formData.requestDate || !formData.quantity) {
      toast.error("필수 항목을 모두 입력해주세요.");
      return;
    }

    const workOrderData = {
      ...formData,
      category,
      workProcesses,
      createdAt: new Date().toISOString()
    };

    if (onSave) {
      onSave(workOrderData);
    }

    toast.success("작업지시서가 저장되었습니다.");
    onBack();
  };

  return (
    <div className="min-h-screen bg-muted/30 dark:bg-background">
      {/* 헤더 */}
      <div className="bg-card border-b border-border sticky top-0 z-10">
        <div className="px-4 md:px-6 py-4">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div className="flex items-center gap-4">
              <Button
                variant="outline"
                onClick={onBack}
                size="sm"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                뒤로가기
              </Button>
              <div>
                <h1 className="text-xl md:text-2xl font-bold">작업지시서 작성</h1>
                <p className="text-xs text-muted-foreground mt-0.5">
                  새로운 작업지시서를 작성합니다
                </p>
              </div>
            </div>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" onClick={onBack}>
                취소
              </Button>
              <Button size="sm" onClick={handleSubmit} className="bg-blue-600 hover:bg-blue-700">
                <Save className="h-4 w-4 mr-2" />
                저장
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 폼 본문 */}
      <div className="px-4 md:px-6 py-6">
        <div className="space-y-6">
          {/* 카테고리 선택 */}
          <Card className="border border-border/50 shadow-sm">
            <CardHeader className="border-b border-border bg-muted/30 dark:bg-muted/10">
              <CardTitle className="text-lg">카테고리 선택</CardTitle>
            </CardHeader>
            <CardContent className="p-4 md:p-6">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <Button
                  variant={category === "스크린" ? "default" : "outline"}
                  className={category === "스크린" ? "bg-blue-600 hover:bg-blue-700" : ""}
                  onClick={() => setCategory("스크린")}
                >
                  스크린 생산
                </Button>
                <Button
                  variant={category === "슬랫" ? "default" : "outline"}
                  className={category === "슬랫" ? "bg-blue-600 hover:bg-blue-700" : ""}
                  onClick={() => setCategory("슬랫")}
                >
                  슬랫 생산
                </Button>
                <Button
                  variant={category === "절곡" ? "default" : "outline"}
                  className={category === "절곡" ? "bg-blue-600 hover:bg-blue-700" : ""}
                  onClick={() => setCategory("절곡")}
                >
                  절곡 생산
                </Button>
              </div>
              {category && (
                <div className="mt-3 text-sm text-muted-foreground">
                  선택된 카테고리: <span className="font-semibold text-blue-600">{category}</span>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 기본 정보 */}
          <Card className="border border-border/50 shadow-sm">
            <CardHeader className="border-b border-border bg-muted/30 dark:bg-muted/10">
              <CardTitle className="text-lg">기본 정보</CardTitle>
            </CardHeader>
            <CardContent className="p-4 md:p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
                <div className="space-y-2">
                  <Label htmlFor="buyer">고객사 *</Label>
                  <Input
                    id="buyer"
                    placeholder="고객사명을 입력하세요"
                    value={formData.buyer}
                    onChange={(e) => handleInputChange("buyer", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="siteName">설치 현장 *</Label>
                  <Input
                    id="siteName"
                    placeholder="설치 현장명을 입력하세요"
                    value={formData.siteName}
                    onChange={(e) => handleInputChange("siteName", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="productName">제품명 *</Label>
                  <Input
                    id="productName"
                    placeholder="제품명을 입력하세요"
                    value={formData.productName}
                    onChange={(e) => handleInputChange("productName", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="quantity">수량 (EA) *</Label>
                  <Input
                    id="quantity"
                    type="number"
                    placeholder="수량을 입력하세요"
                    value={formData.quantity}
                    onChange={(e) => handleInputChange("quantity", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="orderDate">수주일 *</Label>
                  <Input
                    id="orderDate"
                    type="date"
                    value={formData.orderDate}
                    onChange={(e) => handleInputChange("orderDate", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="requestDate">납기일 *</Label>
                  <Input
                    id="requestDate"
                    type="date"
                    value={formData.requestDate}
                    onChange={(e) => handleInputChange("requestDate", e.target.value)}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="workPriority">작업 우선순위</Label>
                  <Select value={formData.workPriority} onValueChange={(value) => handleInputChange("workPriority", value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="우선순위 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="1">1순위 (긴급)</SelectItem>
                      <SelectItem value="2">2순위 (높음)</SelectItem>
                      <SelectItem value="3">3순위 (보통)</SelectItem>
                      <SelectItem value="4">4순위 (낮음)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="status">작업 상태</Label>
                  <Select value={formData.status} onValueChange={(value) => handleInputChange("status", value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="대기">대기</SelectItem>
                      <SelectItem value="작업중">작업중</SelectItem>
                      <SelectItem value="검수">검수</SelectItem>
                      <SelectItem value="완료">완료</SelectItem>
                      <SelectItem value="작업취소">작업취소</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 작업 공정 */}
          <Card className="border border-border/50 shadow-sm">
            <CardHeader className="border-b border-border bg-muted/30 dark:bg-muted/10">
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">작업 공정</CardTitle>
                <Button size="sm" variant="outline" onClick={addProcess}>
                  <Plus className="h-4 w-4 mr-2" />
                  공정 추가
                </Button>
              </div>
            </CardHeader>
            <CardContent className="p-4 md:p-6">
              <div className="space-y-4">
                {workProcesses.map((process, index) => (
                  <div key={index} className="p-4 border border-border rounded-lg bg-muted/20 dark:bg-muted/10">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="font-semibold text-sm">공정 {index + 1}</h4>
                      {workProcesses.length > 1 && (
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => removeProcess(index)}
                          className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-100 dark:hover:bg-red-900/20"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label>공정명</Label>
                        <Input
                          placeholder="공정명 (예: 재단, 조립)"
                          value={process.process}
                          onChange={(e) => handleProcessChange(index, "process", e.target.value)}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>담당자</Label>
                        <Input
                          placeholder="담당자명"
                          value={process.assignee}
                          onChange={(e) => handleProcessChange(index, "assignee", e.target.value)}
                        />
                      </div>
                      <div className="space-y-2 md:col-span-2">
                        <Label>작업 내용</Label>
                        <Input
                          placeholder="작업 내용 설명"
                          value={process.content}
                          onChange={(e) => handleProcessChange(index, "content", e.target.value)}
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>상태</Label>
                        <Select value={process.status} onValueChange={(value) => handleProcessChange(index, "status", value)}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="대기">대기</SelectItem>
                            <SelectItem value="진행중">진행중</SelectItem>
                            <SelectItem value="완료">완료</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* 특기사항 */}
          <Card className="border border-border/50 shadow-sm">
            <CardHeader className="border-b border-border bg-muted/30 dark:bg-muted/10">
              <CardTitle className="text-lg">특기사항</CardTitle>
            </CardHeader>
            <CardContent className="p-4 md:p-6">
              <Textarea
                placeholder="특기사항을 입력하세요"
                className="min-h-[120px]"
                value={formData.specialNotes}
                onChange={(e) => handleInputChange("specialNotes", e.target.value)}
              />
            </CardContent>
          </Card>

          {/* 하단 버튼 */}
          <div className="flex justify-end gap-3 pt-4">
            <Button variant="outline" onClick={onBack}>
              취소
            </Button>
            <Button onClick={handleSubmit} className="bg-blue-600 hover:bg-blue-700">
              <Save className="h-4 w-4 mr-2" />
              작업지시서 저장
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
