import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Badge } from "@/components/ui/badge";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Upload, X, Package } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { toast } from "sonner";
import { phoneCN, description as descSchema, requiredEnum, imageFiles } from "@/lib/forms/schemas";

interface Product {
  id: string;
  name: string;
  price: number;
  image_url?: string;
}

interface AfterSalesRequestDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderId: string;
  orderNumber: string;
  products: Product[];
  onSuccess?: () => void;
}

const AFTER_SALES_TYPES = [
  { value: "return", label: "退货", description: "商品退回，申请退款", color: "bg-red-50 text-red-700" },
  { value: "exchange", label: "换货", description: "更换相同或不同商品", color: "bg-blue-50 text-blue-700" },
  { value: "repair", label: "维修", description: "商品维修服务", color: "bg-green-50 text-green-700" },
] as const;

const REASONS = [
  { value: "quality_issue", label: "质量问题" },
  { value: "wrong_item", label: "商品错误" },
  { value: "not_as_described", label: "与描述不符" },
  { value: "damaged", label: "运输损坏" },
  { value: "personal_reason", label: "个人原因" },
] as const;

const schema = z.object({
  productId: z.string({ required_error: "请选择商品" }).min(1, "请选择商品"),
  type: requiredEnum(["return", "exchange", "repair"], "请选择售后类型"),
  reason: requiredEnum(
    ["quality_issue", "wrong_item", "not_as_described", "damaged", "personal_reason"],
    "请选择申请原因",
  ),
  description: descSchema(5, 500),
  contactPhone: phoneCN,
  images: imageFiles({ maxCount: 6, maxSizeMB: 5 }).default([]),
});
type Values = z.infer<typeof schema>;

export function AfterSalesRequestDialog({
  open,
  onOpenChange,
  orderId,
  orderNumber,
  products,
  onSuccess,
}: AfterSalesRequestDialogProps) {
  const { user } = useAuth();
  const [step, setStep] = useState(1);
  const [submitting, setSubmitting] = useState(false);
  const [uploading, setUploading] = useState(false);

  const form = useForm<Values>({
    resolver: zodResolver(schema),
    defaultValues: {
      productId: "",
      type: undefined as unknown as Values["type"],
      reason: undefined as unknown as Values["reason"],
      description: "",
      contactPhone: "",
      images: [],
    },
    mode: "onBlur",
  });

  const selectedProductId = form.watch("productId");
  const selectedProduct = products.find((p) => p.id === selectedProductId) ?? null;
  const images = form.watch("images") ?? [];

  const handleClose = () => {
    setStep(1);
    form.reset();
    onOpenChange(false);
  };

  const handleNext = async () => {
    const fieldsByStep: Record<number, (keyof Values)[]> = {
      1: ["productId"],
      2: ["type", "reason"],
    };
    const ok = await form.trigger(fieldsByStep[step]);
    if (ok) setStep((s) => s + 1);
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    const next = [...images, ...files].slice(0, 6);
    form.setValue("images", next, { shouldValidate: true });
    event.target.value = "";
  };

  const removeImage = (index: number) => {
    const next = images.filter((_, i) => i !== index);
    form.setValue("images", next, { shouldValidate: true });
  };

  const uploadImages = async (files: File[]): Promise<string[]> => {
    if (files.length === 0) return [];
    setUploading(true);
    try {
      const urls: string[] = [];
      for (const image of files) {
        const fileExt = image.name.split(".").pop();
        const fileName = `${Math.random().toString(36).substring(2)}.${fileExt}`;
        const filePath = `after-sales/${fileName}`;
        const { error: uploadError } = await supabase.storage
          .from("product-images")
          .upload(filePath, image);
        if (uploadError) throw uploadError;
        const { data } = supabase.storage.from("product-images").getPublicUrl(filePath);
        urls.push(data.publicUrl);
      }
      return urls;
    } finally {
      setUploading(false);
    }
  };

  const onSubmit = async (values: Values) => {
    if (!user) return;
    try {
      setSubmitting(true);
      const imageUrls = await uploadImages(values.images);
      const { error } = await supabase.from("after_sales_requests").insert({
        user_id: user.id,
        order_id: orderId,
        product_id: values.productId,
        type: values.type,
        status: "pending",
        reason: values.reason,
        description: values.description,
        images: imageUrls.length > 0 ? imageUrls : null,
      });
      if (error) throw error;
      toast.success("售后申请已提交，我们会尽快处理");
      onSuccess?.();
      handleClose();
    } catch (err) {
      console.error("提交失败:", err);
      toast.error("提交失败，请稍后重试");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
        <DialogHeader>
          <DialogTitle>申请售后服务</DialogTitle>
          <DialogDescription>
            订单号: {orderNumber} - 第{step}/3步
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 overflow-hidden">
            <div className="flex-1 overflow-y-auto">
              {/* Step 1: 选择商品 */}
              {step === 1 && (
                <FormField
                  control={form.control}
                  name="productId"
                  render={({ field }) => (
                    <FormItem className="space-y-4">
                      <div>
                        <FormLabel className="text-base font-medium">请选择需要售后的商品</FormLabel>
                        <p className="text-sm text-muted-foreground mt-1">选择您要申请售后服务的商品</p>
                      </div>
                      <div className="grid gap-3">
                        {products.map((product) => (
                          <Card
                            key={product.id}
                            className={`cursor-pointer transition-all ${
                              field.value === product.id
                                ? "ring-2 ring-primary bg-primary/5"
                                : "hover:shadow-md"
                            }`}
                            onClick={() => field.onChange(product.id)}
                          >
                            <CardContent className="p-4">
                              <div className="flex items-center space-x-4">
                                <div className="w-16 h-16 bg-muted rounded-lg overflow-hidden flex-shrink-0">
                                  {product.image_url ? (
                                    <img src={product.image_url} alt={product.name} className="w-full h-full object-cover" />
                                  ) : (
                                    <div className="w-full h-full flex items-center justify-center">
                                      <Package className="h-6 w-6 text-muted-foreground" />
                                    </div>
                                  )}
                                </div>
                                <div className="flex-1">
                                  <h4 className="font-semibold">{product.name}</h4>
                                  <p className="text-lg font-bold text-primary">¥{product.price}</p>
                                </div>
                                {field.value === product.id && <Badge variant="default">已选择</Badge>}
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              )}

              {/* Step 2: 类型 + 原因 */}
              {step === 2 && (
                <div className="space-y-6">
                  <FormField
                    control={form.control}
                    name="type"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-base font-medium">售后类型</FormLabel>
                        <p className="text-sm text-muted-foreground mt-1">请选择您需要的售后服务类型</p>
                        <FormControl>
                          <RadioGroup value={field.value} onValueChange={field.onChange} className="mt-3">
                            {AFTER_SALES_TYPES.map((type) => (
                              <div key={type.value} className="flex items-center space-x-3">
                                <RadioGroupItem value={type.value} id={type.value} />
                                <div className="flex-1">
                                  <Label htmlFor={type.value} className="cursor-pointer">
                                    <div className="flex items-center justify-between">
                                      <div>
                                        <span className="font-medium">{type.label}</span>
                                        <p className="text-sm text-muted-foreground">{type.description}</p>
                                      </div>
                                      <Badge className={type.color} variant="secondary">{type.label}</Badge>
                                    </div>
                                  </Label>
                                </div>
                              </div>
                            ))}
                          </RadioGroup>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="reason"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-base font-medium">申请原因</FormLabel>
                        <Select value={field.value} onValueChange={field.onChange}>
                          <FormControl>
                            <SelectTrigger className="mt-2">
                              <SelectValue placeholder="请选择申请原因" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {REASONS.map((reason) => (
                              <SelectItem key={reason.value} value={reason.value}>
                                {reason.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              )}

              {/* Step 3: 详情 */}
              {step === 3 && (
                <div className="space-y-6">
                  <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-base font-medium">问题详细描述</FormLabel>
                        <p className="text-sm text-muted-foreground mt-1">详细描述将帮助我们更好地处理您的申请（5-500 字）</p>
                        <FormControl>
                          <Textarea {...field} placeholder="请详细描述您遇到的问题..." className="mt-2 min-h-[100px]" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="contactPhone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-base font-medium">联系电话</FormLabel>
                        <FormControl>
                          <Input {...field} placeholder="请输入您的手机号" className="mt-2" inputMode="numeric" />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name="images"
                    render={() => (
                      <FormItem>
                        <FormLabel className="text-base font-medium">相关图片</FormLabel>
                        <p className="text-sm text-muted-foreground mt-1">
                          上传相关图片有助于我们更好地了解问题（最多 6 张，每张不超过 5MB）
                        </p>
                        <div className="mt-3 grid grid-cols-3 gap-3">
                          {images.map((image, index) => (
                            <div key={index} className="relative group">
                              <img
                                src={URL.createObjectURL(image)}
                                alt={`预览图片 ${index + 1}`}
                                className="w-full h-24 object-cover rounded-lg border"
                              />
                              <Button
                                type="button"
                                variant="destructive"
                                size="sm"
                                className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0 opacity-0 group-hover:opacity-100 transition-opacity"
                                onClick={() => removeImage(index)}
                              >
                                <X className="h-3 w-3" />
                              </Button>
                            </div>
                          ))}
                          {images.length < 6 && (
                            <label className="flex flex-col items-center justify-center w-full h-24 border-2 border-dashed border-muted-foreground/25 rounded-lg cursor-pointer hover:border-muted-foreground/50 transition-colors">
                              <div className="flex flex-col items-center justify-center">
                                <Upload className="h-6 w-6 text-muted-foreground/50" />
                                <span className="text-xs text-muted-foreground mt-1">上传图片</span>
                              </div>
                              <input type="file" multiple accept="image/*" className="hidden" onChange={handleFileSelect} />
                            </label>
                          )}
                        </div>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              )}
            </div>

            <DialogFooter className="flex justify-between mt-4">
              <div>
                {step > 1 && (
                  <Button type="button" variant="outline" onClick={() => setStep((s) => s - 1)}>
                    上一步
                  </Button>
                )}
              </div>
              <div className="space-x-2">
                <Button type="button" variant="outline" onClick={handleClose}>取消</Button>
                {step < 3 ? (
                  <Button type="button" onClick={handleNext}>下一步</Button>
                ) : (
                  <Button type="submit" disabled={submitting || uploading}>
                    {submitting ? "提交中..." : uploading ? "上传中..." : "提交申请"}
                  </Button>
                )}
              </div>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
