import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
  TrendingUp,
  Users,
  Target,
  Award,
  Calendar,
  DollarSign,
  BarChart3,
  Trophy,
  Star,
} from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, Legend } from 'recharts';

export function SalesPerformance() {
  const [selectedPeriod, setSelectedPeriod] = useState('월간');
  const [selectedYear, setSelectedYear] = useState('2025');

  // 월별 실적 데이터
  const monthlyData = [
    { month: '1월', 목표: 500, 실적: 450, 달성률: 90 },
    { month: '2월', 목표: 500, 실적: 520, 달성률: 104 },
    { month: '3월', 목표: 550, 실적: 480, 달성률: 87 },
    { month: '4월', 목표: 600, 실적: 610, 달성률: 102 },
    { month: '5월', 목표: 600, 실적: 580, 달성률: 97 },
    { month: '6월', 목표: 650, 실적: 650, 달성률: 100 },
  ];

  // 영업사원별 실적
  const salesPersonData = [
    {
      id: 'SP001',
      name: '정수진',
      team: '영업1팀',
      target: 1200,
      achievement: 1350,
      rate: 112.5,
      orders: 45,
      newCustomers: 8,
      rank: 1
    },
    {
      id: 'SP002',
      name: '김철수',
      team: '영업1팀',
      target: 1200,
      achievement: 1180,
      rate: 98.3,
      orders: 38,
      newCustomers: 6,
      rank: 2
    },
    {
      id: 'SP003',
      name: '박민수',
      team: '영업2팀',
      target: 1000,
      achievement: 1050,
      rate: 105,
      orders: 42,
      newCustomers: 5,
      rank: 3
    },
    {
      id: 'SP004',
      name: '이영희',
      team: '영업2팀',
      target: 1000,
      achievement: 950,
      rate: 95,
      orders: 35,
      newCustomers: 4,
      rank: 4
    },
    {
      id: 'SP005',
      name: '강민호',
      team: '영업3팀',
      target: 800,
      achievement: 820,
      rate: 102.5,
      orders: 28,
      newCustomers: 7,
      rank: 5
    },
  ];

  // 제품별 매출
  const productSales = [
    { product: '스크린 기본형', sales: 1850, quantity: 120, growth: 15 },
    { product: '슬랫 표준형', sales: 1420, quantity: 85, growth: 8 },
    { product: '절곡 제품', sales: 980, quantity: 65, growth: -5 },
    { product: '스크린 프리미엄', sales: 750, quantity: 38, growth: 22 },
  ];

  const periods = ['월간', '분기', '연간'];
  const years = ['2025', '2024', '2023'];

  const totalTarget = salesPersonData.reduce((sum, sp) => sum + sp.target, 0);
  const totalAchievement = salesPersonData.reduce((sum, sp) => sum + sp.achievement, 0);
  const overallRate = (totalAchievement / totalTarget) * 100;
  const totalOrders = salesPersonData.reduce((sum, sp) => sum + sp.orders, 0);
  const totalNewCustomers = salesPersonData.reduce((sum, sp) => sum + sp.newCustomers, 0);

  const getRateColor = (rate: number) => {
    if (rate >= 100) return 'text-green-600';
    if (rate >= 90) return 'text-blue-600';
    if (rate >= 80) return 'text-orange-600';
    return 'text-red-600';
  };

  const getRateBadge = (rate: number) => {
    if (rate >= 100) return <Badge variant="default">목표달성</Badge>;
    if (rate >= 90) return <Badge variant="secondary">우수</Badge>;
    if (rate >= 80) return <Badge variant="outline">양호</Badge>;
    return <Badge variant="destructive">미달</Badge>;
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="mb-2">영업 실적</h1>
          <p className="text-muted-foreground">
            영업사원별 실적 및 목표 달성률을 관리합니다.
          </p>
        </div>
        <div className="flex gap-2">
          <Select value={selectedPeriod} onValueChange={setSelectedPeriod}>
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {periods.map((period) => (
                <SelectItem key={period} value={period}>
                  {period}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select value={selectedYear} onValueChange={setSelectedYear}>
            <SelectTrigger className="w-[100px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {years.map((year) => (
                <SelectItem key={year} value={year}>
                  {year}년
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 주요 지표 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>전체 달성률</CardTitle>
            <Target className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{overallRate.toFixed(1)}%</div>
            <p className="text-xs text-muted-foreground">
              {totalAchievement.toLocaleString()} / {totalTarget.toLocaleString()}백만원
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>총 수주건수</CardTitle>
            <BarChart3 className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{totalOrders}건</div>
            <p className="text-xs text-muted-foreground">전체 수주</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>신규 고객</CardTitle>
            <Users className="h-4 w-4 text-purple-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">{totalNewCustomers}개사</div>
            <p className="text-xs text-muted-foreground">신규 확보</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>평균 수주액</CardTitle>
            <DollarSign className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {Math.round(totalAchievement / totalOrders)}백만원
            </div>
            <p className="text-xs text-muted-foreground">건당 평균</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 월별 실적 추이 */}
        <Card>
          <CardHeader>
            <CardTitle>월별 실적 추이</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300} minHeight={300}>
              <BarChart data={monthlyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar dataKey="목표" fill="#94a3b8" />
                <Bar dataKey="실적" fill="#3b82f6" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* 달성률 추이 */}
        <Card>
          <CardHeader>
            <CardTitle>달성률 추이</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300} minHeight={300}>
              <LineChart data={monthlyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line type="monotone" dataKey="달성률" stroke="#10b981" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* 영업사원별 실적 */}
      <Card>
        <CardHeader>
          <CardTitle>영업사원별 실적</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 데스크톱 테이블 뷰 */}
          <div className="hidden md:block">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left p-3">순위</th>
                  <th className="text-left p-3">이름</th>
                  <th className="text-left p-3">팀</th>
                  <th className="text-left p-3">목표</th>
                  <th className="text-left p-3">실적</th>
                  <th className="text-left p-3">달성률</th>
                  <th className="text-left p-3">수주건수</th>
                  <th className="text-left p-3">신규고객</th>
                  <th className="text-left p-3">평가</th>
                </tr>
              </thead>
              <tbody>
                {salesPersonData.map((person) => (
                  <tr key={person.id} className="border-b hover:bg-accent">
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        {person.rank === 1 && <Trophy className="h-4 w-4 text-yellow-500" />}
                        {person.rank === 2 && <Award className="h-4 w-4 text-gray-400" />}
                        {person.rank === 3 && <Award className="h-4 w-4 text-orange-600" />}
                        <span className="font-medium">{person.rank}위</span>
                      </div>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <Users className="h-4 w-4 text-muted-foreground" />
                        <span className="font-medium">{person.name}</span>
                      </div>
                    </td>
                    <td className="p-3">
                      <Badge variant="outline">{person.team}</Badge>
                    </td>
                    <td className="p-3">{person.target.toLocaleString()}백만원</td>
                    <td className="p-3 font-medium">{person.achievement.toLocaleString()}백만원</td>
                    <td className="p-3">
                      <span className={`font-medium ${getRateColor(person.rate)}`}>
                        {person.rate.toFixed(1)}%
                      </span>
                    </td>
                    <td className="p-3">{person.orders}건</td>
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <Star className="h-4 w-4 text-yellow-500" />
                        {person.newCustomers}개사
                      </div>
                    </td>
                    <td className="p-3">
                      {getRateBadge(person.rate)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 모바일 카드 뷰 */}
          <div className="md:hidden space-y-4">
            {salesPersonData.map((person) => (
              <Card key={person.id}>
                <CardContent className="p-4 space-y-3">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      {person.rank === 1 && <Trophy className="h-5 w-5 text-yellow-500" />}
                      {person.rank === 2 && <Award className="h-5 w-5 text-gray-400" />}
                      {person.rank === 3 && <Award className="h-5 w-5 text-orange-600" />}
                      <div>
                        <p className="font-medium">{person.name}</p>
                        <p className="text-sm text-muted-foreground">{person.team}</p>
                      </div>
                    </div>
                    <div className="flex flex-col gap-1 items-end">
                      <Badge variant="outline">{person.rank}위</Badge>
                      {getRateBadge(person.rate)}
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="space-y-1">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">목표</span>
                        <span>{person.target.toLocaleString()}백만</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">실적</span>
                        <span className="font-medium">{person.achievement.toLocaleString()}백만</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">달성률</span>
                        <span className={`font-medium ${getRateColor(person.rate)}`}>
                          {person.rate.toFixed(1)}%
                        </span>
                      </div>
                    </div>
                    <div className="space-y-1">
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">수주</span>
                        <span>{person.orders}건</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">신규고객</span>
                        <span>{person.newCustomers}개사</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">평균</span>
                        <span>{Math.round(person.achievement / person.orders)}백만</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 제품별 매출 */}
      <Card>
        <CardHeader>
          <CardTitle>제품별 매출 현황</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {productSales.map((product, index) => (
              <div key={index} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex-1">
                  <p className="font-medium">{product.product}</p>
                  <p className="text-sm text-muted-foreground">{product.quantity}개 판매</p>
                </div>
                <div className="flex items-center gap-4">
                  <div className="text-right">
                    <p className="font-medium">{product.sales.toLocaleString()}백만원</p>
                    <div className="flex items-center gap-1 text-sm">
                      {product.growth >= 0 ? (
                        <TrendingUp className="h-3 w-3 text-green-500" />
                      ) : (
                        <TrendingUp className="h-3 w-3 text-red-500 rotate-180" />
                      )}
                      <span className={product.growth >= 0 ? 'text-green-500' : 'text-red-500'}>
                        {Math.abs(product.growth)}%
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}