import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Badge } from './ui/badge';
import { Input } from './ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
  ShoppingCart,
  TrendingUp,
  TrendingDown,
  Package,
  DollarSign,
  Calendar,
  Search,
  Building2,
  Clock,
  CheckCircle,
  AlertCircle,
} from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, Legend, PieChart as RechartsPieChart, Pie, Cell } from 'recharts';

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

  // 월별 구매 현황
  const monthlyPurchase = [
    { month: '1월', 금액: 350, 발주건수: 28 },
    { month: '2월', 금액: 420, 발주건수: 32 },
    { month: '3월', 금액: 465, 발주건수: 35 },
    { month: '4월', 금액: 510, 발주건수: 38 },
    { month: '5월', 금액: 485, 발주건수: 36 },
    { month: '6월', 금액: 520, 발주건수: 40 },
  ];

  // 공급처별 구매 현황
  const supplierPurchase = [
    { supplier: '(주)알루미늄공업', amount: 125000000, orders: 12, rate: 26.8 },
    { supplier: '철강유통', amount: 155000000, orders: 15, rate: 33.2 },
    { supplier: '모터산업', amount: 95000000, orders: 10, rate: 20.4 },
    { supplier: '대한패브릭', amount: 85000000, orders: 8, rate: 18.2 },
    { supplier: '기타', amount: 6000000, orders: 5, rate: 1.4 },
  ];

  // 품목 분류별 구매액
  const categoryPurchase = [
    { name: '원자재', value: 365, color: '#3b82f6' },
    { name: '부품', value: 104, color: '#10b981' },
    { name: '부자재', value: 12, color: '#f59e0b' },
    { name: '설비', value: 0, color: '#8b5cf6' },
  ];

  // 발주 현황 요약
  const orderSummary = [
    { status: '승인대기', count: 1, amount: 5500000, color: 'orange' },
    { status: '발주중', count: 2, amount: 22550000, color: 'blue' },
    { status: '입고완료', count: 2, amount: 23100000, color: 'green' },
  ];

  // 납기 준수율 추이
  const deliveryCompliance = [
    { month: '1월', 준수율: 92, 평균납기일: 8.5 },
    { month: '2월', 준수율: 88, 평균납기일: 9.2 },
    { month: '3월', 준수율: 95, 평균납기일: 7.8 },
    { month: '4월', 준수율: 91, 평균납기일: 8.3 },
    { month: '5월', 준수율: 94, 평균납기일: 7.5 },
    { month: '6월', 준수율: 96, 평균납기일: 7.2 },
  ];

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

  const totalPurchase = monthlyPurchase.reduce((sum, m) => sum + m.금액, 0);
  const totalOrders = monthlyPurchase.reduce((sum, m) => sum + m.발주건수, 0);
  const avgOrderAmount = totalPurchase / totalOrders;
  const avgDeliveryCompliance = deliveryCompliance.reduce((sum, d) => sum + d.준수율, 0) / deliveryCompliance.length;

  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>
            <DollarSign className="h-4 w-4 text-blue-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{totalPurchase.toFixed(0)}백만원</div>
            <p className="text-xs text-muted-foreground">
              전월 대비 +7.2%
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>발주 건수</CardTitle>
            <ShoppingCart className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{totalOrders}건</div>
            <p className="text-xs text-muted-foreground">
              평균 {avgOrderAmount.toFixed(1)}백만원/건
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>납기 준수율</CardTitle>
            <CheckCircle className="h-4 w-4 text-purple-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">{avgDeliveryCompliance.toFixed(1)}%</div>
            <p className="text-xs text-muted-foreground">
              평균 7.6일 소요
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle>활성 공급처</CardTitle>
            <Building2 className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">5개사</div>
            <p className="text-xs text-muted-foreground">
              거래중
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 발주 현황 요약 */}
      <Card>
        <CardHeader>
          <CardTitle>발주 현황 요약</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {orderSummary.map((item, index) => (
              <div key={index} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm text-muted-foreground">{item.status}</span>
                  {item.status === '승인대기' && <AlertCircle className="h-4 w-4 text-orange-500" />}
                  {item.status === '발주중' && <Clock className="h-4 w-4 text-blue-500" />}
                  {item.status === '입고완료' && <CheckCircle className="h-4 w-4 text-green-500" />}
                </div>
                <div className="space-y-1">
                  <p className="text-2xl font-bold">{item.count}건</p>
                  <p className="text-sm text-muted-foreground">
                    {(item.amount / 1000000).toFixed(1)}백만원
                  </p>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <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={monthlyPurchase}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip />
                <Legend />
                <Bar yAxisId="left" dataKey="금액" fill="#3b82f6" name="구매금액 (백만원)" />
                <Line yAxisId="right" type="monotone" dataKey="발주건수" stroke="#10b981" strokeWidth={2} name="발주건수" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* 품목 분류별 구매액 */}
        <Card>
          <CardHeader>
            <CardTitle>품목 분류별 구매액</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300} minHeight={300}>
              <RechartsPieChart>
                <Pie
                  data={categoryPurchase}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, value }) => `${name} ${value}백만원`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {categoryPurchase.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </RechartsPieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* 납기 준수율 추이 */}
      <Card>
        <CardHeader>
          <CardTitle>납기 준수율 추이</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={300} minHeight={300}>
            <LineChart data={deliveryCompliance}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="month" />
              <YAxis yAxisId="left" domain={[0, 100]} />
              <YAxis yAxisId="right" orientation="right" domain={[0, 15]} />
              <Tooltip />
              <Legend />
              <Line yAxisId="left" type="monotone" dataKey="준수율" stroke="#10b981" strokeWidth={2} name="준수율 (%)" />
              <Line yAxisId="right" type="monotone" dataKey="평균납기일" stroke="#f59e0b" strokeWidth={2} name="평균납기일 (일)" />
            </LineChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      {/* 공급처별 구매 현황 */}
      <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>
                </tr>
              </thead>
              <tbody>
                {supplierPurchase.map((supplier, index) => (
                  <tr key={index} className="border-b hover:bg-accent">
                    <td className="p-3">
                      <div className="flex items-center gap-2">
                        <Building2 className="h-4 w-4 text-muted-foreground" />
                        <span className="font-medium">{supplier.supplier}</span>
                      </div>
                    </td>
                    <td className="p-3 font-medium">
                      {(supplier.amount / 1000000).toFixed(0)}백만원
                    </td>
                    <td className="p-3">{supplier.orders}건</td>
                    <td className="p-3">
                      <Badge variant="outline">{supplier.rate.toFixed(1)}%</Badge>
                    </td>
                    <td className="p-3">
                      <div className="w-full bg-secondary rounded-full h-2">
                        <div
                          className="bg-blue-500 h-2 rounded-full"
                          style={{ width: `${supplier.rate}%` }}
                        />
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="md:hidden space-y-3">
            {supplierPurchase.map((supplier, index) => (
              <Card key={index}>
                <CardContent className="p-4">
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Building2 className="h-4 w-4 text-muted-foreground" />
                        <span className="font-medium">{supplier.supplier}</span>
                      </div>
                      <Badge variant="outline">{supplier.rate.toFixed(1)}%</Badge>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">구매금액</span>
                      <span className="font-medium">{(supplier.amount / 1000000).toFixed(0)}백만원</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">발주건수</span>
                      <span>{supplier.orders}건</span>
                    </div>
                    <div className="w-full bg-secondary rounded-full h-2">
                      <div
                        className="bg-blue-500 h-2 rounded-full"
                        style={{ width: `${supplier.rate}%` }}
                      />
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}