import { useState, useEffect } from "react";
import { Header } from "@/components/layout/Header";
import { useAuth } from "@/contexts/AuthContext";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { 
  Package, 
  RotateCcw, 
  Settings, 
  Clock, 
  CheckCircle, 
  XCircle,
  Plus,
  Search,
  Filter,
  AlertCircle,
  Truck,
  MessageSquare,
  Phone,
  Star,
  ArrowLeft,
  Home
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { useNavigate } from "react-router-dom";
import { PLACEHOLDER_PRODUCT_SMALL } from "@/utils/placeholderImage";

interface AfterSalesRequest {
  id: string;
  user_id: string;
  order_id: string;
  product_id: string;
  type: 'return' | 'exchange' | 'repair';
  status: 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';
  reason: string;
  description: string;
  images?: string[];
  admin_notes?: string;
  tracking_number?: string;
  refund_amount?: number;
  processed_by?: string;
  processed_at?: string;
  created_at: string;
  updated_at: string;
  orderNumber?: string;
  productName?: string;
  productImage?: string;
  createdAt?: string;
  updatedAt?: string;
  amount?: number;
}

export default function AfterSalesPage() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState("requests");
  const [showNewRequest, setShowNewRequest] = useState(false);
  const [afterSalesRequests, setAfterSalesRequests] = useState<AfterSalesRequest[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const [loading, setLoading] = useState(true);
  const [userOrders, setUserOrders] = useState<any[]>([]);
  const { toast } = useToast();
  const navigate = useNavigate();

  // 新申请表单状态
  const [newRequest, setNewRequest] = useState({
    orderNumber: "",
    productName: "",
    type: "",
    reason: "",
    description: "",
    images: [] as File[]
  });

  useEffect(() => {
    if (user) {
      fetchAfterSalesRequests();
      fetchUserOrders();
    }
  }, [user]);

  const fetchAfterSalesRequests = async () => {
    if (!user) return;
    
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('after_sales_requests')
        .select('*')
        .eq('user_id', user.id)
        .order('created_at', { ascending: false });

      if (error) throw error;
      
      // 获取关联的订单和商品信息
      const requestsWithDetails = await Promise.all((data || []).map(async (request) => {
        // 获取订单信息
        const { data: orderData } = await supabase
          .from('orders')
          .select('order_number')
          .eq('id', request.order_id)
          .single();

        // 获取商品信息
        const { data: productData } = await supabase
          .from('products')
          .select('name, image_url')
          .eq('id', request.product_id)
          .single();

        return {
          ...request,
          orderNumber: orderData?.order_number || '',
          productName: productData?.name || '',
          productImage: productData?.image_url || PLACEHOLDER_PRODUCT_SMALL,
          createdAt: new Date(request.created_at).toISOString().split('T')[0],
          updatedAt: new Date(request.updated_at).toISOString().split('T')[0],
          amount: request.refund_amount || 0
        };
      }));
      
      setAfterSalesRequests(requestsWithDetails as AfterSalesRequest[]);
    } catch (error) {
      console.error('获取售后申请失败:', error);
      toast({
        title: "获取失败",
        description: "无法获取售后申请列表",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const fetchUserOrders = async () => {
    if (!user) return;
    
    try {
      const { data, error } = await supabase
        .from('orders')
        .select(`
          id,
          order_number,
          total_amount,
          order_items (
            id,
            product_id,
            products (
              id,
              name,
              image_url
            )
          )
        `)
        .eq('user_id', user.id)
        .order('created_at', { ascending: false });

      if (error) throw error;
      setUserOrders(data || []);
    } catch (error) {
      console.error('获取订单失败:', error);
    }
  };

  const handleSubmitRequest = async () => {
    if (!user || !newRequest.orderNumber || !newRequest.type || !newRequest.reason || !newRequest.description) {
      toast({
        title: "提交失败",
        description: "请填写所有必填字段",
        variant: "destructive"
      });
      return;
    }

    try {
      // 查找对应的订单和商品
      const selectedOrder = userOrders.find(order => order.order_number === newRequest.orderNumber);
      if (!selectedOrder) {
        toast({
          title: "提交失败",
          description: "找不到对应的订单",
          variant: "destructive"
        });
        return;
      }

      const orderItem = selectedOrder.order_items[0]; // 假设选择第一个商品
      if (!orderItem) {
        toast({
          title: "提交失败",
          description: "订单中没有商品",
          variant: "destructive"
        });
        return;
      }

      const { error } = await supabase
        .from('after_sales_requests')
        .insert({
          user_id: user.id,
          order_id: selectedOrder.id,
          product_id: orderItem.product_id,
          type: newRequest.type,
          reason: newRequest.reason,
          description: newRequest.description,
          images: []
        });

      if (error) throw error;

      setNewRequest({
        orderNumber: "",
        productName: "",
        type: "",
        reason: "",
        description: "",
        images: []
      });
      setShowNewRequest(false);

      toast({
        title: "申请提交成功",
        description: "您的售后申请已提交，我们将在1-2个工作日内处理"
      });

      // 重新获取售后申请列表
      fetchAfterSalesRequests();
    } catch (error) {
      console.error('提交售后申请失败:', error);
      toast({
        title: "提交失败",
        description: "无法提交售后申请，请稍后重试",
        variant: "destructive"
      });
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "pending": return "bg-yellow-100 text-yellow-800 border-yellow-200";
      case "approved": return "bg-blue-100 text-blue-800 border-blue-200";
      case "processing": return "bg-orange-100 text-orange-800 border-orange-200";
      case "completed": return "bg-green-100 text-green-800 border-green-200";
      case "rejected": return "bg-red-100 text-red-800 border-red-200";
      default: return "bg-muted text-foreground border-border";
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case "pending": return "待审核";
      case "approved": return "已审核";
      case "processing": return "处理中";
      case "completed": return "已完成";
      case "rejected": return "已拒绝";
      default: return status;
    }
  };

  const getTypeText = (type: string) => {
    switch (type) {
      case "return": return "退货";
      case "exchange": return "换货";
      case "repair": return "维修";
      default: return type;
    }
  };

  const getReasonText = (reason: string) => {
    switch (reason) {
      case "quality_issue": return "质量问题";
      case "wrong_item": return "商品错误";
      case "not_as_described": return "与描述不符";
      case "damaged": return "运输损坏";
      case "personal_reason": return "个人原因";
      default: return reason;
    }
  };

  const filteredRequests = afterSalesRequests.filter(request => {
    const matchesSearch = (request.orderNumber || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (request.productName || '').toLowerCase().includes(searchTerm.toLowerCase());
    const matchesFilter = filterStatus === "all" || request.status === filterStatus;
    return matchesSearch && matchesFilter;
  });

  if (!user) {
    return (
      <div className="min-h-screen bg-background">
        <Header />
        <div className="container max-w-7xl mx-auto p-6">
          <Card className="text-center py-12">
            <CardContent>
              <AlertCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-medium text-foreground mb-2">请先登录</h3>
              <p className="text-muted-foreground">您需要登录后才能查看售后服务</p>
            </CardContent>
          </Card>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />
      
      <div className="container max-w-7xl mx-auto p-6">
        <div className="mb-8">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">售后服务</h1>
              <p className="text-sm sm:text-base text-muted-foreground">管理您的退换货申请，查看处理进度</p>
            </div>
            <div className="flex items-center">
              <Button 
                onClick={() => navigate(-1)} 
                variant="outline" 
                size="sm"
                className="flex items-center space-x-1 sm:space-x-2"
              >
                <ArrowLeft className="h-3 w-3 sm:h-4 sm:w-4" />
                <span className="text-sm">返回</span>
              </Button>
            </div>
          </div>
        </div>

        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="requests">我的申请</TabsTrigger>
            <TabsTrigger value="policy">服务政策</TabsTrigger>
            <TabsTrigger value="contact">联系客服</TabsTrigger>
          </TabsList>

          {/* 我的申请 */}
          <TabsContent value="requests" className="space-y-6">
            <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
              <div className="flex flex-col md:flex-row gap-4 flex-1">
                <div className="relative flex-1 max-w-md">
                  <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索订单号或商品名称..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <Select value={filterStatus} onValueChange={setFilterStatus}>
                  <SelectTrigger className="w-[150px]">
                    <Filter className="w-4 h-4 mr-2" />
                    <SelectValue placeholder="状态筛选" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="pending">待审核</SelectItem>
                    <SelectItem value="processing">处理中</SelectItem>
                    <SelectItem value="completed">已完成</SelectItem>
                    <SelectItem value="rejected">已拒绝</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button onClick={() => setShowNewRequest(true)}>
                <Plus className="w-4 h-4 mr-2" />
                新申请
              </Button>
            </div>

            {/* 申请列表 */}
            <div className="grid gap-4">
              {loading ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                </div>
              ) : filteredRequests.map((request) => (
                <Card key={request.id} className="border border-border">
                  <CardContent className="p-6">
                    <div className="flex flex-col lg:flex-row gap-6">
                      <div className="flex gap-4">
                        <img
                          src={request.productImage}
                          alt={request.productName}
                          className="w-20 h-20 object-cover rounded-lg bg-muted"
                        />
                        <div className="flex-1">
                          <h3 className="font-semibold text-foreground">{request.productName}</h3>
                          <p className="text-sm text-muted-foreground">订单号: {request.orderNumber}</p>
                          <p className="text-sm text-muted-foreground">金额: ¥{request.amount?.toFixed(2)}</p>
                        </div>
                      </div>

                      <div className="flex-1 space-y-3">
                        <div className="flex flex-wrap gap-2">
                          <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                            {getTypeText(request.type)}
                          </Badge>
                          <Badge className={getStatusColor(request.status)}>
                            {getStatusText(request.status)}
                          </Badge>
                        </div>
                        
                        <div>
                          <p className="text-sm font-medium">申请原因: {getReasonText(request.reason)}</p>
                          <p className="text-sm text-muted-foreground mt-1">{request.description}</p>
                        </div>

                        <div className="flex justify-between text-xs text-muted-foreground">
                          <span>申请时间: {request.createdAt}</span>
                          <span>更新时间: {request.updatedAt}</span>
                        </div>
                      </div>

                      <div className="flex flex-col gap-2">
                        <Button variant="outline" size="sm">
                          查看详情
                        </Button>
                        {request.status === "pending" && (
                          <Button variant="ghost" size="sm" className="text-destructive">
                            取消申请
                          </Button>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}

              {!loading && filteredRequests.length === 0 && (
                <Card className="text-center py-12">
                  <CardContent>
                    <Package className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-foreground mb-2">暂无售后申请</h3>
                    <p className="text-muted-foreground mb-4">您还没有提交过售后申请</p>
                    <Button onClick={() => setShowNewRequest(true)}>
                      <Plus className="w-4 h-4 mr-2" />
                      提交新申请
                    </Button>
                  </CardContent>
                </Card>
              )}
            </div>
          </TabsContent>

          {/* 服务政策 */}
          <TabsContent value="policy" className="space-y-6">
            <div className="grid gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <RotateCcw className="w-5 h-5 text-blue-500" />
                    退换货政策
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <h4 className="font-semibold mb-2">7天无理由退货</h4>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li>• 商品需保持原包装完整</li>
                        <li>• 附件配件需齐全</li>
                        <li>• 不影响二次销售</li>
                        <li>• 支持在线申请</li>
                      </ul>
                    </div>
                    <div>
                      <h4 className="font-semibold mb-2">15天免费换货</h4>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li>• 商品质量问题</li>
                        <li>• 发错商品</li>
                        <li>• 运输损坏</li>
                        <li>• 功能故障</li>
                      </ul>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Settings className="w-5 h-5 text-green-500" />
                    维修服务
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid md:grid-cols-3 gap-6">
                    <div>
                      <h4 className="font-semibold mb-2">免费维修</h4>
                      <p className="text-sm text-muted-foreground">
                        质量问题导致的故障，在保修期内提供免费维修服务
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold mb-2">付费维修</h4>
                      <p className="text-sm text-muted-foreground">
                        人为损坏或超出保修期的设备提供付费维修服务
                      </p>
                    </div>
                    <div>
                      <h4 className="font-semibold mb-2">上门服务</h4>
                      <p className="text-sm text-muted-foreground">
                        部分大件商品提供上门检测和维修服务
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Clock className="w-5 h-5 text-orange-500" />
                    处理时效
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid md:grid-cols-2 gap-6">
                    <div className="space-y-3">
                      <div className="flex justify-between items-center p-3 bg-muted rounded-lg">
                        <span className="font-medium">申请审核</span>
                        <span className="text-sm text-muted-foreground">1-2个工作日</span>
                      </div>
                      <div className="flex justify-between items-center p-3 bg-muted rounded-lg">
                        <span className="font-medium">商品寄回</span>
                        <span className="text-sm text-muted-foreground">3-5个工作日</span>
                      </div>
                    </div>
                    <div className="space-y-3">
                      <div className="flex justify-between items-center p-3 bg-muted rounded-lg">
                        <span className="font-medium">质检处理</span>
                        <span className="text-sm text-muted-foreground">1-3个工作日</span>
                      </div>
                      <div className="flex justify-between items-center p-3 bg-muted rounded-lg">
                        <span className="font-medium">退款到账</span>
                        <span className="text-sm text-muted-foreground">1-7个工作日</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 联系客服 */}
          <TabsContent value="contact" className="space-y-6">
            <div className="grid md:grid-cols-2 gap-6">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <MessageSquare className="w-5 h-5 text-blue-500" />
                    在线客服
                  </CardTitle>
                  <CardDescription>7×24小时在线服务</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="flex items-center justify-between p-4 border border-border rounded-lg">
                      <div>
                        <h4 className="font-medium">AI智能客服</h4>
                        <p className="text-sm text-muted-foreground">即时回复，快速解决常见问题</p>
                      </div>
                      <Button>开始对话</Button>
                    </div>
                    <div className="flex items-center justify-between p-4 border border-border rounded-lg">
                      <div>
                        <h4 className="font-medium">人工客服</h4>
                        <p className="text-sm text-muted-foreground">专业客服，处理复杂问题</p>
                      </div>
                      <Button variant="outline">排队等待</Button>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Phone className="w-5 h-5 text-green-500" />
                    电话客服
                  </CardTitle>
                  <CardDescription>专业客服团队为您服务</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="text-center p-4 border border-border rounded-lg">
                      <h4 className="text-lg font-semibold">400-888-8888</h4>
                      <p className="text-sm text-muted-foreground">服务时间：9:00-21:00</p>
                    </div>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span>商品咨询</span>
                        <span className="text-muted-foreground">按1</span>
                      </div>
                      <div className="flex justify-between">
                        <span>售后服务</span>
                        <span className="text-muted-foreground">按2</span>
                      </div>
                      <div className="flex justify-between">
                        <span>投诉建议</span>
                        <span className="text-muted-foreground">按3</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            <Card>
              <CardHeader>
                <CardTitle>服务评价</CardTitle>
                <CardDescription>我们重视您的每一次体验反馈</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid md:grid-cols-3 gap-6 text-center">
                  <div className="space-y-2">
                    <div className="text-3xl font-bold text-primary">4.9</div>
                    <div className="flex justify-center">
                      {[1,2,3,4,5].map((star) => (
                        <Star key={star} className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                      ))}
                    </div>
                    <p className="text-sm text-muted-foreground">客户满意度</p>
                  </div>
                  <div className="space-y-2">
                    <div className="text-3xl font-bold text-primary">2分钟</div>
                    <p className="text-sm text-muted-foreground">平均响应时间</p>
                  </div>
                  <div className="space-y-2">
                    <div className="text-3xl font-bold text-primary">98%</div>
                    <p className="text-sm text-muted-foreground">问题解决率</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* 新申请对话框 */}
        <Dialog open={showNewRequest} onOpenChange={setShowNewRequest}>
          <DialogContent className="max-w-2xl max-h-[90vh]">
            <DialogHeader>
              <DialogTitle>提交售后申请</DialogTitle>
              <DialogDescription>
                请填写详细信息，我们将尽快处理您的申请
              </DialogDescription>
            </DialogHeader>
            
            <ScrollArea className="max-h-[60vh]">
              <div className="space-y-4 p-1">
                <div>
                  <Label htmlFor="orderNumber">选择订单 *</Label>
                  <Select value={newRequest.orderNumber} onValueChange={(value) => {
                    const order = userOrders.find(o => o.order_number === value);
                    setNewRequest({
                      ...newRequest, 
                      orderNumber: value,
                      productName: order?.order_items?.[0]?.products?.name || ''
                    });
                  }}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择要申请售后的订单" />
                    </SelectTrigger>
                    <SelectContent>
                      {userOrders.map((order) => (
                        <SelectItem key={order.id} value={order.order_number}>
                          {order.order_number} - ¥{order.total_amount}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {newRequest.orderNumber && (
                  <div>
                    <Label>选择商品</Label>
                    <div className="text-sm text-muted-foreground p-2 bg-muted rounded">
                      {newRequest.productName || '商品信息'}
                    </div>
                  </div>
                )}

                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="type">申请类型 *</Label>
                    <Select value={newRequest.type} onValueChange={(value) => setNewRequest({...newRequest, type: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择申请类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="return">退货</SelectItem>
                        <SelectItem value="exchange">换货</SelectItem>
                        <SelectItem value="repair">维修</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div>
                    <Label htmlFor="reason">申请原因 *</Label>
                    <Select value={newRequest.reason} onValueChange={(value) => setNewRequest({...newRequest, reason: value})}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择原因" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="quality_issue">质量问题</SelectItem>
                        <SelectItem value="wrong_item">商品错误</SelectItem>
                        <SelectItem value="not_as_described">与描述不符</SelectItem>
                        <SelectItem value="damaged">运输损坏</SelectItem>
                        <SelectItem value="personal_reason">个人原因</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div>
                  <Label htmlFor="description">问题描述 *</Label>
                  <Textarea
                    id="description"
                    placeholder="请详细描述遇到的问题..."
                    value={newRequest.description}
                    onChange={(e) => setNewRequest({...newRequest, description: e.target.value})}
                    className="min-h-[100px]"
                  />
                </div>

                <div>
                  <Label>上传图片 (可选)</Label>
                  <div className="border-2 border-dashed border-border rounded-lg p-6 text-center">
                    <Package className="w-8 h-8 text-muted-foreground mx-auto mb-2" />
                    <p className="text-sm text-muted-foreground">点击或拖拽上传商品照片</p>
                    <p className="text-xs text-muted-foreground mt-1">支持 JPG、PNG 格式，最多5张</p>
                  </div>
                </div>
              </div>
            </ScrollArea>
            
            <div className="flex gap-3 justify-end pt-4 border-t">
              <Button variant="outline" onClick={() => setShowNewRequest(false)}>
                取消
              </Button>
              <Button onClick={handleSubmitRequest}>
                提交申请
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </div>
  );
}