import { useState, useEffect, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Alert, AlertDescription } from "./ui/alert";
import { Checkbox } from "./ui/checkbox";
import { Plus, Trash2, RotateCw, Info, Edit, X } from "lucide-react";
import { toast } from "sonner@2.0.3";

// 절곡 단계 데이터
export interface BendingStep {
  id: string;
  step: number;        // 좌표/단계
  angle: number;       // 각도
  innerRadius: number; // 안족 (inner radius)
  length: number;      // 길이
  remarks?: string;    // 비고
  
  // 추가 계산 필드
  inputValue?: number;          // 입력
  yieldRate?: number;           // 연실율 (%)
  afterYieldRate?: number;      // 연실율계산 후
  total?: number;               // 합계
  shading?: string;             // 음영
  angleDisplay?: string;        // a각표시
}

interface BendingDataInputProps {
  value?: BendingStep[];
  onChange?: (data: BendingStep[]) => void;
}

export function BendingDataInput({ value = [], onChange }: BendingDataInputProps) {
  const [bendingSteps, setBendingSteps] = useState<BendingStep[]>(value);
  const [isEditMode, setIsEditMode] = useState(false);
  const [selectedSteps, setSelectedSteps] = useState<Set<string>>(new Set());
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    setBendingSteps(value);
  }, [value]);

  useEffect(() => {
    if (onChange) {
      onChange(bendingSteps);
    }
    drawBendingVisualization();
  }, [bendingSteps]);

  const addStep = () => {
    const newStep: BendingStep = {
      id: `step-${Date.now()}`,
      step: bendingSteps.length + 1,
      angle: 90,
      innerRadius: 1,
      length: 100,
      remarks: "",
      inputValue: 0,
      yieldRate: 0,
      afterYieldRate: 0,
      total: 0,
      shading: "",
      angleDisplay: ""
    };
    setBendingSteps([...bendingSteps, newStep]);
  };

  const removeStep = (id: string) => {
    const filtered = bendingSteps.filter(step => step.id !== id);
    // 단계 번호 재정렬
    const reordered = filtered.map((step, index) => ({
      ...step,
      step: index + 1
    }));
    setBendingSteps(reordered);
  };

  const removeSelectedSteps = () => {
    if (selectedSteps.size === 0) {
      toast.error("삭제할 항목을 선택해주세요.");
      return;
    }
    const filtered = bendingSteps.filter(step => !selectedSteps.has(step.id));
    // 단계 번호 재정렬
    const reordered = filtered.map((step, index) => ({
      ...step,
      step: index + 1
    }));
    setBendingSteps(reordered);
    setSelectedSteps(new Set());
    toast.success(`${selectedSteps.size}개 항목이 삭제되었습니다.`);
  };

  const clearAllSteps = () => {
    if (bendingSteps.length === 0) {
      toast.error("삭제할 데이터가 없습니다.");
      return;
    }
    setBendingSteps([]);
    setSelectedSteps(new Set());
    setIsEditMode(false);
    toast.success("모든 데이터가 초기화되었습니다.");
  };

  const toggleStepSelection = (id: string) => {
    const newSelected = new Set(selectedSteps);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    setSelectedSteps(newSelected);
  };

  const toggleAllSteps = () => {
    if (selectedSteps.size === bendingSteps.length) {
      setSelectedSteps(new Set());
    } else {
      setSelectedSteps(new Set(bendingSteps.map(step => step.id)));
    }
  };

  const updateStep = (id: string, field: keyof BendingStep, value: any) => {
    setBendingSteps(bendingSteps.map(step => {
      if (step.id === id) {
        const updatedStep = { ...step, [field]: value };
        
        // 자동 계산: 연실율계산 후 = 입력값 * (1 + 연실율/100)
        if (field === "inputValue" || field === "yieldRate") {
          const inputVal = field === "inputValue" ? value : (step.inputValue || 0);
          const yieldVal = field === "yieldRate" ? value : (step.yieldRate || 0);
          updatedStep.afterYieldRate = inputVal * (1 + yieldVal / 100);
        }
        
        // 자동 계산: 합계 = 연실율계산 후 + 길이
        if (field === "afterYieldRate" || field === "length" || field === "inputValue" || field === "yieldRate") {
          const afterYield = field === "afterYieldRate" ? value : 
                            (field === "inputValue" || field === "yieldRate" ? 
                             updatedStep.afterYieldRate : (step.afterYieldRate || 0));
          const lengthVal = field === "length" ? value : (step.length || 0);
          updatedStep.total = (afterYield || 0) + lengthVal;
        }
        
        return updatedStep;
      }
      return step;
    }));
  };

  // 절곡 시각화 그리기
  const drawBendingVisualization = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    // 캔버스 초기화
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (bendingSteps.length === 0) {
      // 안내 텍스트
      ctx.fillStyle = "#999";
      ctx.font = "14px sans-serif";
      ctx.textAlign = "center";
      ctx.fillText("절곡 단계를 추가하면 여기에 시각화됩니다", canvas.width / 2, canvas.height / 2);
      return;
    }

    // 그리기 시작점
    let currentX = 50;
    let currentY = canvas.height / 2;
    let currentAngle = 0; // 현재 방향 각도 (라디안)

    // 배경 그리드
    ctx.strokeStyle = "#f0f0f0";
    ctx.lineWidth = 0.5;
    for (let i = 0; i < canvas.width; i += 20) {
      ctx.beginPath();
      ctx.moveTo(i, 0);
      ctx.lineTo(i, canvas.height);
      ctx.stroke();
    }
    for (let i = 0; i < canvas.height; i += 20) {
      ctx.beginPath();
      ctx.moveTo(0, i);
      ctx.lineTo(canvas.width, i);
      ctx.stroke();
    }

    // 절곡 라인 그리기
    ctx.strokeStyle = "#2563eb";
    ctx.lineWidth = 3;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.beginPath();
    ctx.moveTo(currentX, currentY);

    bendingSteps.forEach((step, index) => {
      const scaledLength = step.length * 1.5; // 시각화를 위한 스케일

      // 현재 방향으로 직선 그리기
      const endX = currentX + Math.cos(currentAngle) * scaledLength;
      const endY = currentY + Math.sin(currentAngle) * scaledLength;
      ctx.lineTo(endX, endY);

      // 각도 표시 (A각)
      if (step.angle !== 180) {
        const angleRad = (step.angle - 180) * Math.PI / 180;
        const arcRadius = 20;
        
        // 각도 호 그리기
        ctx.save();
        ctx.strokeStyle = "#dc2626";
        ctx.lineWidth = 1.5;
        ctx.beginPath();
        ctx.arc(
          endX, 
          endY, 
          arcRadius, 
          currentAngle, 
          currentAngle + angleRad,
          angleRad < 0
        );
        ctx.stroke();
        
        // 각도 텍스트
        const textAngle = currentAngle + angleRad / 2;
        const textX = endX + Math.cos(textAngle) * (arcRadius + 15);
        const textY = endY + Math.sin(textAngle) * (arcRadius + 15);
        ctx.fillStyle = "#dc2626";
        ctx.font = "bold 12px sans-serif";
        ctx.textAlign = "center";
        ctx.fillText(`${step.angle}°`, textX, textY);
        ctx.restore();
      }

      // 단계 번호 표시
      ctx.save();
      ctx.fillStyle = "#2563eb";
      ctx.beginPath();
      ctx.arc(endX, endY, 8, 0, Math.PI * 2);
      ctx.fill();
      ctx.fillStyle = "white";
      ctx.font = "bold 10px sans-serif";
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(step.step.toString(), endX, endY);
      ctx.restore();

      // 길이 표시
      const midX = (currentX + endX) / 2;
      const midY = (currentY + endY) / 2;
      const perpAngle = currentAngle + Math.PI / 2;
      const labelX = midX + Math.cos(perpAngle) * 15;
      const labelY = midY + Math.sin(perpAngle) * 15;
      
      ctx.save();
      ctx.fillStyle = "#059669";
      ctx.font = "11px sans-serif";
      ctx.textAlign = "center";
      ctx.fillText(`L${step.step}: ${step.length}`, labelX, labelY);
      ctx.restore();

      // 다음 각도 계산
      currentAngle += (step.angle - 180) * Math.PI / 180;
      currentX = endX;
      currentY = endY;
    });

    ctx.stroke();

    // 음영 효과 (절곡된 면)
    if (bendingSteps.length > 1) {
      ctx.save();
      ctx.globalAlpha = 0.1;
      ctx.fillStyle = "#3b82f6";
      
      currentX = 50;
      currentY = canvas.height / 2;
      currentAngle = 0;
      
      ctx.beginPath();
      ctx.moveTo(currentX, currentY);
      
      bendingSteps.forEach(step => {
        const scaledLength = step.length * 1.5;
        const endX = currentX + Math.cos(currentAngle) * scaledLength;
        const endY = currentY + Math.sin(currentAngle) * scaledLength;
        
        // 두께를 고려한 평행선
        const thickness = 10;
        const perpAngle = currentAngle + Math.PI / 2;
        const offsetX = Math.cos(perpAngle) * thickness;
        const offsetY = Math.sin(perpAngle) * thickness;
        
        ctx.lineTo(endX, endY);
        currentAngle += (step.angle - 180) * Math.PI / 180;
        currentX = endX;
        currentY = endY;
      });
      
      // 닫기
      currentX = 50;
      currentY = canvas.height / 2;
      currentAngle = 0;
      const thickness = 10;
      
      bendingSteps.reverse().forEach(step => {
        const scaledLength = step.length * 1.5;
        const perpAngle = currentAngle + Math.PI / 2;
        const offsetX = Math.cos(perpAngle) * thickness;
        const offsetY = Math.sin(perpAngle) * thickness;
        
        currentAngle += (step.angle - 180) * Math.PI / 180;
        const endX = currentX + Math.cos(currentAngle) * scaledLength + offsetX;
        const endY = currentY + Math.sin(currentAngle) * scaledLength + offsetY;
        ctx.lineTo(endX, endY);
        currentX += Math.cos(currentAngle) * scaledLength;
        currentY += Math.sin(currentAngle) * scaledLength;
      });
      bendingSteps.reverse();
      
      ctx.closePath();
      ctx.fill();
      ctx.restore();
    }
  };

  return (
    <div className="space-y-4">
      {/* 계산 안내 */}
      <Alert className="border-blue-200 bg-blue-50">
        <Info className="h-4 w-4 text-blue-600" />
        <AlertDescription className="text-sm text-blue-900">
          <strong>자동 계산 안내:</strong> 연실율계산 후 = 입력값 × (1 + 연실율/100), 합계 = 연실율계산 후 + 길이
        </AlertDescription>
      </Alert>

      {/* 절곡 단계 입력 테이블 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">절곡 단계 입력</CardTitle>
            <div className="flex items-center gap-2">
              {isEditMode && (
                <>
                  <Button 
                    onClick={removeSelectedSteps} 
                    size="sm" 
                    variant="destructive"
                    disabled={selectedSteps.size === 0}
                  >
                    <Trash2 className="h-4 w-4 mr-1" />
                    선택 삭제 ({selectedSteps.size})
                  </Button>
                  <Button 
                    onClick={() => {
                      setIsEditMode(false);
                      setSelectedSteps(new Set());
                    }} 
                    size="sm" 
                    variant="outline"
                  >
                    <X className="h-4 w-4 mr-1" />
                    취소
                  </Button>
                </>
              )}
              {!isEditMode && (
                <>
                  <Button onClick={addStep} size="sm" variant="outline">
                    <Plus className="h-4 w-4 mr-1" />
                    단계 추가
                  </Button>
                  <Button 
                    onClick={() => setIsEditMode(true)} 
                    size="sm" 
                    variant="outline"
                    disabled={bendingSteps.length === 0}
                  >
                    <Edit className="h-4 w-4 mr-1" />
                    편집
                  </Button>
                  <Button 
                    onClick={clearAllSteps} 
                    size="sm" 
                    variant="outline"
                    disabled={bendingSteps.length === 0}
                  >
                    <RotateCw className="h-4 w-4 mr-1" />
                    값 초기화
                  </Button>
                </>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  {isEditMode && (
                    <TableHead className="w-12">
                      <Checkbox 
                        checked={bendingSteps.length > 0 && selectedSteps.size === bendingSteps.length}
                        onCheckedChange={toggleAllSteps}
                      />
                    </TableHead>
                  )}
                  <TableHead className="w-16">단계</TableHead>
                  <TableHead>각도 (°)</TableHead>
                  <TableHead>안족 (R)</TableHead>
                  <TableHead>길이 (mm)</TableHead>
                  <TableHead>입력</TableHead>
                  <TableHead>연실율 (%)</TableHead>
                  <TableHead>연실율계산 후</TableHead>
                  <TableHead>합계</TableHead>
                  <TableHead>음영</TableHead>
                  <TableHead>a각표시</TableHead>
                  <TableHead>비고</TableHead>
                  {!isEditMode && <TableHead className="w-20">작업</TableHead>}
                </TableRow>
              </TableHeader>
              <TableBody>
                {bendingSteps.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={isEditMode ? 13 : 12} className="text-center text-muted-foreground py-8">
                      절곡 단계를 추가해주세요
                    </TableCell>
                  </TableRow>
                ) : (
                  bendingSteps.map((step) => (
                    <TableRow key={step.id}>
                      {isEditMode && (
                        <TableCell>
                          <Checkbox 
                            checked={selectedSteps.has(step.id)}
                            onCheckedChange={() => toggleStepSelection(step.id)}
                          />
                        </TableCell>
                      )}
                      <TableCell>
                        <Badge variant="secondary">{step.step}</Badge>
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.angle}
                          onChange={(e) => updateStep(step.id, "angle", parseFloat(e.target.value) || 0)}
                          className="w-20"
                          min="0"
                          max="180"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.innerRadius}
                          onChange={(e) => updateStep(step.id, "innerRadius", parseFloat(e.target.value) || 0)}
                          className="w-20"
                          min="0"
                          step="0.1"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.length}
                          onChange={(e) => updateStep(step.id, "length", parseFloat(e.target.value) || 0)}
                          className="w-24"
                          min="0"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.inputValue || 0}
                          onChange={(e) => updateStep(step.id, "inputValue", parseFloat(e.target.value) || 0)}
                          className="w-20"
                          min="0"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.yieldRate || 0}
                          onChange={(e) => updateStep(step.id, "yieldRate", parseFloat(e.target.value) || 0)}
                          className="w-20"
                          min="0"
                          max="100"
                          step="0.1"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.afterYieldRate || 0}
                          onChange={(e) => updateStep(step.id, "afterYieldRate", parseFloat(e.target.value) || 0)}
                          className="w-24"
                          min="0"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="number"
                          value={step.total || 0}
                          onChange={(e) => updateStep(step.id, "total", parseFloat(e.target.value) || 0)}
                          className="w-20"
                          min="0"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="text"
                          value={step.shading || ""}
                          onChange={(e) => updateStep(step.id, "shading", e.target.value)}
                          placeholder="음영"
                          className="w-24"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="text"
                          value={step.angleDisplay || ""}
                          onChange={(e) => updateStep(step.id, "angleDisplay", e.target.value)}
                          placeholder="a각"
                          className="w-24"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          type="text"
                          value={step.remarks || ""}
                          onChange={(e) => updateStep(step.id, "remarks", e.target.value)}
                          placeholder="비고"
                          className="w-32"
                        />
                      </TableCell>
                      {!isEditMode && (
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeStep(step.id)}
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 뷰 */}
          <div className="md:hidden space-y-3 mt-4">
            {bendingSteps.map((step) => (
              <Card key={step.id} className="border-2">
                <CardContent className="pt-4 space-y-3">
                  <div className="flex items-center justify-between mb-2">
                    <Badge variant="secondary">단계 {step.step}</Badge>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeStep(step.id)}
                    >
                      <Trash2 className="h-4 w-4 text-red-600" />
                    </Button>
                  </div>
                  
                  <div className="space-y-3">
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <Label className="text-xs">각도 (°)</Label>
                        <Input
                          type="number"
                          value={step.angle}
                          onChange={(e) => updateStep(step.id, "angle", parseFloat(e.target.value) || 0)}
                          min="0"
                          max="180"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">안족 (R)</Label>
                        <Input
                          type="number"
                          value={step.innerRadius}
                          onChange={(e) => updateStep(step.id, "innerRadius", parseFloat(e.target.value) || 0)}
                          min="0"
                          step="0.1"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">길이 (mm)</Label>
                        <Input
                          type="number"
                          value={step.length}
                          onChange={(e) => updateStep(step.id, "length", parseFloat(e.target.value) || 0)}
                          min="0"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">입력</Label>
                        <Input
                          type="number"
                          value={step.inputValue || 0}
                          onChange={(e) => updateStep(step.id, "inputValue", parseFloat(e.target.value) || 0)}
                          min="0"
                        />
                      </div>
                    </div>
                    
                    <div className="border-t pt-3">
                      <Label className="text-xs mb-2 block">연실율 계산</Label>
                      <div className="grid grid-cols-2 gap-3">
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">연실율 (%)</Label>
                          <Input
                            type="number"
                            value={step.yieldRate || 0}
                            onChange={(e) => updateStep(step.id, "yieldRate", parseFloat(e.target.value) || 0)}
                            min="0"
                            max="100"
                            step="0.1"
                          />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">연실율계산 후</Label>
                          <Input
                            type="number"
                            value={step.afterYieldRate || 0}
                            onChange={(e) => updateStep(step.id, "afterYieldRate", parseFloat(e.target.value) || 0)}
                            min="0"
                          />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">합계</Label>
                          <Input
                            type="number"
                            value={step.total || 0}
                            onChange={(e) => updateStep(step.id, "total", parseFloat(e.target.value) || 0)}
                            min="0"
                          />
                        </div>
                        <div className="space-y-1">
                          <Label className="text-xs text-muted-foreground">음영</Label>
                          <Input
                            type="text"
                            value={step.shading || ""}
                            onChange={(e) => updateStep(step.id, "shading", e.target.value)}
                            placeholder="음영"
                          />
                        </div>
                      </div>
                    </div>
                    
                    <div className="border-t pt-3 grid grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <Label className="text-xs">a각표시</Label>
                        <Input
                          type="text"
                          value={step.angleDisplay || ""}
                          onChange={(e) => updateStep(step.id, "angleDisplay", e.target.value)}
                          placeholder="a각"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">비고</Label>
                        <Input
                          type="text"
                          value={step.remarks || ""}
                          onChange={(e) => updateStep(step.id, "remarks", e.target.value)}
                          placeholder="비고"
                        />
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 절곡 시각화 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">절곡 형태 미리보기</CardTitle>
            <div className="flex items-center space-x-2 text-xs text-muted-foreground">
              <div className="flex items-center space-x-1">
                <div className="w-3 h-3 bg-blue-600 rounded" />
                <span>절곡선</span>
              </div>
              <div className="flex items-center space-x-1">
                <div className="w-3 h-3 bg-red-600 rounded" />
                <span>각도(A각)</span>
              </div>
              <div className="flex items-center space-x-1">
                <div className="w-3 h-3 bg-green-600 rounded" />
                <span>길이</span>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="bg-white rounded-lg border-2 border-gray-200 p-4">
            <canvas
              ref={canvasRef}
              width={800}
              height={400}
              className="w-full h-auto"
              style={{ maxHeight: "400px" }}
            />
          </div>
          
          {bendingSteps.length > 0 && (
            <div className="mt-4 p-3 bg-blue-50 rounded-lg border border-blue-200">
              <div className="text-sm space-y-1">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                  <p className="text-blue-900">
                    <span className="font-medium">총 절곡 단계:</span> {bendingSteps.length}단계
                  </p>
                  <p className="text-blue-900">
                    <span className="font-medium">총 전개 길이:</span>{" "}
                    {bendingSteps.reduce((sum, step) => sum + step.length, 0).toFixed(1)}mm
                  </p>
                  <p className="text-blue-900">
                    <span className="font-medium">총 입력값:</span>{" "}
                    {bendingSteps.reduce((sum, step) => sum + (step.inputValue || 0), 0).toFixed(1)}
                  </p>
                  <p className="text-blue-900">
                    <span className="font-medium">총 합계:</span>{" "}
                    {bendingSteps.reduce((sum, step) => sum + (step.total || 0), 0).toFixed(1)}
                  </p>
                </div>
                <p className="text-xs text-blue-700 mt-2 pt-2 border-t border-blue-200">
                  * 파란색 선은 절곡선, 빨간색 호는 절곡 각도(A각), 녹색 텍스트는 각 구간의 길이를 나타냅니다.
                </p>
                <p className="text-xs text-blue-700">
                  * 연실율계산 후 = 입력값 × (1 + 연실율/100), 합계 = 연실율계산 후 + 길이
                </p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
