import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { DollarSign, TrendingUp, TrendingDown } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { useState, useMemo } from "react";
import { useData } from "../contexts/DataContext";

export function SalesOverviewWidget() {
  const { salesOrders, receivables } = useData();
  const [selectedPeriod, setSelectedPeriod] = useState("today");

  // 실제 데이터로부터 매출 계산
  const salesData = useMemo(() => {
    const now = new Date();
    const today = now.toISOString().split('T')[0];
    const thisMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
    const thisYear = `${now.getFullYear()}`;

    // 완료된 주문만 매출로 계산
    const completedOrders = salesOrders.filter(order => 
      order.status === 'completed' || order.status === 'shipping'
    );

    // 일별 매출
    const dailyOrders = completedOrders.filter(order => order.orderDate.startsWith(today));
    const dailyActual = dailyOrders.reduce((sum, order) => sum + order.totalAmount, 0);

    // 월별 매출
    const monthlyOrders = completedOrders.filter(order => order.orderDate.startsWith(thisMonth));
    const monthlyActual = monthlyOrders.reduce((sum, order) => sum + order.totalAmount, 0);

    // 연간 매출
    const yearlyOrders = completedOrders.filter(order => order.orderDate.startsWith(thisYear));
    const yearlyActual = yearlyOrders.reduce((sum, order) => sum + order.totalAmount, 0);

    // 미수금 계산
    const totalReceivable = receivables.filter(r => r.status !== 'paid').reduce((sum, r) => sum + r.amount, 0);
    const paidReceivable = receivables.filter(r => r.status === 'paid').reduce((sum, r) => sum + r.amount, 0);
    const totalAmount = totalReceivable + paidReceivable;
    const collectionRate = totalAmount > 0 ? (paidReceivable / totalAmount) * 100 : 0;

    return {
      daily: { 
        actual: dailyActual, 
        target: 50000000, 
        achievement: dailyActual > 0 ? Math.round((dailyActual / 50000000) * 100) : 0, 
        receivable: totalReceivable,
        collected: paidReceivable,
        collectionRate: Math.round(collectionRate * 10) / 10
      },
      monthly: { 
        actual: monthlyActual, 
        target: 1500000000, 
        achievement: Math.round((monthlyActual / 1500000000) * 100),
        receivable: totalReceivable,
        collected: paidReceivable,
        collectionRate: Math.round(collectionRate * 10) / 10
      },
      yearly: { 
        actual: yearlyActual, 
        target: 10000000000, 
        achievement: Math.round((yearlyActual / 10000000000) * 100),
        receivable: totalReceivable,
        collected: paidReceivable,
        collectionRate: Math.round(collectionRate * 10) / 10
      }
    };
  }, [salesOrders, receivables]);

  const getPeriodData = () => {
    switch (selectedPeriod) {
      case "today":
        return salesData.daily;
      case "month":
        return salesData.monthly;
      case "year":
        return salesData.yearly;
      default:
        return salesData.daily;
    }
  };

  const periodData = getPeriodData();
  const isPositiveGrowth = periodData.achievement >= 100;

  return (
    <Card className="h-full">
      <CardHeader className="flex flex-row items-center justify-between pb-3">
        <CardTitle className="flex items-center gap-2">
          <DollarSign className="h-5 w-5 text-blue-600" />
          매출 현황
        </CardTitle>
        <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>
          <SelectTrigger className="w-28">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="today">일별</SelectItem>
            <SelectItem value="month">월별</SelectItem>
            <SelectItem value="year">연간</SelectItem>
          </SelectContent>
        </Select>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 실제 매출 */}
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-sm text-muted-foreground">실제 매출</span>
              <Badge variant={periodData.achievement >= 90 ? "default" : "secondary"}>
                달성률 {periodData.achievement}%
              </Badge>
            </div>
            <div className="text-3xl font-bold">
              ₩{(periodData.actual / 1000000).toLocaleString()}M
            </div>
          </div>

          {/* 목표 대비 */}
          <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
            <div>
              <div className="text-sm text-muted-foreground">목표</div>
              <div className="text-lg font-semibold">
                ₩{(periodData.target / 1000000).toLocaleString()}M
              </div>
            </div>
            <div className={`flex items-center gap-1 ${isPositiveGrowth ? 'text-green-600' : 'text-red-600'}`}>
              {isPositiveGrowth ? <TrendingUp className="h-4 w-4" /> : <TrendingDown className="h-4 w-4" />}
              <span className="font-semibold">{periodData.achievement >= 100 ? '+' : ''}{periodData.achievement - 100}%</span>
            </div>
          </div>

          {/* 수금 현황 */}
          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-blue-50 rounded-lg">
              <div className="text-xs text-blue-700 mb-1">미수금</div>
              <div className="text-lg font-semibold text-blue-900">
                ₩{(periodData.receivable / 1000000).toLocaleString()}M
              </div>
            </div>
            <div className="p-3 bg-green-50 rounded-lg">
              <div className="text-xs text-green-700 mb-1">수금률</div>
              <div className="text-lg font-semibold text-green-900">
                {periodData.collectionRate}%
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
