'use client'

import React from 'react'
import { 
  ArrowRight, 
  Edit2, 
  Trash2, 
  User, 
  MapPin, 
  Truck, 
  Clock, 
  History, 
  AlertCircle,
  CheckCircle2,
  Package,
  Calendar
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter, 
  DialogDescription 
} from "@/components/ui/dialog"
import { ScrollArea } from "@/components/ui/scroll-area"
import type { OrderDetailState, OrderDetailHandlers } from '@/backend/hooks/useOrderDetail'

interface Props {
  state: OrderDetailState
  handlers: OrderDetailHandlers
}

export const OrderDetailView = ({ state, handlers }: Props) => {
  const { 
    isLoading, 
    displayData, 
    isDeleteDialogOpen, 
    isDeleting, 
    statusChangeDialog, 
    isChangingStatus, 
    STATUS_LABELS 
  } = state;

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-background text-foreground space-y-4">
        <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin shadow-neon-primary" />
        <p className="font-header text-lg animate-pulse">جاري تحميل تفاصيل الطلب...</p>
      </div>
    );
  }

  if (!displayData) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen bg-background p-8 text-center">
        <div className="bg-destructive/10 p-6 rounded-full mb-6">
          <AlertCircle className="w-16 h-16 text-destructive" />
        </div>
        <h2 className="text-2xl font-header font-bold mb-2">عذراً، الطلب غير موجود</h2>
        <p className="text-muted-foreground mb-8 max-w-md">يبدو أن الرابط الذي اتبعته غير صحيح أو تم حذف الطلب مسبقاً.</p>
        <Button 
          variant="secondary" 
          onClick={handlers.navigateToManagement}
          className="bg-secondary text-secondary-foreground hover:bg-primary hover:text-primary-foreground transition-all"
        >
          <ArrowRight className="ml-2 w-4 h-4" />
          العودة لإدارة الطلبات
        </Button>
      </div>
    );
  }

  // 辅助函数：根据状态获取颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'PENDING': return 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20';
      case 'IN_PROGRESS': return 'bg-primary text-primary-foreground';
      case 'DELIVERED': return 'bg-green-500 text-white';
      case 'CANCELLED': return 'bg-destructive text-destructive-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  return (
    <main className="min-h-screen bg-background text-foreground font-body" dir="rtl">
      {/* 顶部导航与操作栏 */}
      <section className="w-full border-b border-border bg-card/50 backdrop-blur-md sticky top-0 z-10" data-controller-name="شريط التحكم العلوي">
        <div className="container mx-auto px-8 py-4 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button 
              variant="ghost" 
              size="icon" 
              onClick={handlers.navigateToManagement}
              className="hover:bg-muted"
            >
              <ArrowRight className="w-5 h-5" />
            </Button>
            <div>
              <h1 className="text-xl font-header font-bold tracking-tight">
                تفاصيل الطلب <span className="text-primary">#{displayData.order_no || '---'}</span>
              </h1>
              <p className="text-xs text-muted-foreground">عرض وإدارة تفاصيل الطلب وتتبع الحالة</p>
            </div>
          </div>
          
          <div className="flex items-center gap-3">
            <Button 
              variant="outline" 
              onClick={handlers.navigateToEdit}
              className="border-primary/50 text-primary-foreground bg-primary hover:shadow-neon-primary transition-all"
            >
              <Edit2 className="ml-2 w-4 h-4" />
              تعديل الطلب
            </Button>
            <Button 
              variant="destructive" 
              onClick={() => handlers.setIsDeleteDialogOpen(true)}
              className="hover:shadow-lg transition-all"
            >
              <Trash2 className="ml-2 w-4 h-4" />
              حذف الطلب
            </Button>
          </div>
        </div>
      </section>

      {/* 主内容网格 */}
      <section className="container mx-auto px-8 py-8" data-controller-name="لوحة معلومات الطلب">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          
          {/* 右侧：客户与地理位置 */}
          <div className="lg:col-span-4 space-y-6">
            <Card className="overflow-hidden border-border bg-card shadow-md">
              <CardHeader className="bg-muted/30 border-b border-border py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <User className="w-4 h-4 text-primary" />
                  بيانات الزبون
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-4">
                <div className="flex flex-col gap-1">
                  <span className="text-xs text-muted-foreground">اسم الزبون</span>
                  <p className="font-semibold text-base">{displayData.customer_name}</p>
                </div>
                <Separator className="opacity-50" />
                <div className="flex flex-col gap-1">
                  <span className="text-xs text-muted-foreground">رقم الهاتف</span>
                  <p className="font-mono text-base tracking-wider">{displayData.customer_phone}</p>
                </div>
              </CardContent>
            </Card>

            <Card className="overflow-hidden border-border bg-card shadow-md">
              <CardHeader className="bg-muted/30 border-b border-border py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <MapPin className="w-4 h-4 text-primary" />
                  بيانات الموقع
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex flex-col gap-1">
                    <span className="text-xs text-muted-foreground">المحافظة</span>
                    <p className="font-medium">{displayData.governorate_name}</p>
                  </div>
                  <div className="flex flex-col gap-1">
                    <span className="text-xs text-muted-foreground">المنطقة</span>
                    <p className="font-medium">{displayData.area_name}</p>
                  </div>
                </div>
                <Separator className="opacity-50" />
                <div className="flex flex-col gap-1">
                  <span className="text-xs text-muted-foreground">أقرب نقطة دالة</span>
                  <p className="text-sm leading-relaxed">{displayData.nearest_landmark}</p>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 中间：配送与时间戳 */}
          <div className="lg:col-span-4 space-y-6">
            <Card className="overflow-hidden border-border bg-card shadow-md">
              <CardHeader className="bg-muted/30 border-b border-border py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <Truck className="w-4 h-4 text-primary" />
                  بيانات التوصيل
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-4">
                <div className="flex flex-col gap-1">
                  <span className="text-xs text-muted-foreground">السائق المسؤول</span>
                  <p className="font-semibold text-base">{displayData.driver_name || 'لم يتم التعيين بعد'}</p>
                </div>
                <Separator className="opacity-50" />
                <div className="flex flex-col gap-1">
                  <span className="text-xs text-muted-foreground">نوع الطلب</span>
                  <Badge variant="outline" className="w-fit border-primary/20 bg-primary/5 text-primary">
                    <Package className="ml-1 w-3 h-3" />
                    {displayData.order_type}
                  </Badge>
                </div>
              </CardContent>
            </Card>

            <Card className="overflow-hidden border-border bg-card shadow-md">
              <CardHeader className="bg-muted/30 border-b border-border py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <Clock className="w-4 h-4 text-primary" />
                  الطوابع الزمنية
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-4">
                <div className="flex items-center justify-between">
                  <div className="flex flex-col gap-1">
                    <span className="text-xs text-muted-foreground">تاريخ الإنشاء</span>
                    <p className="text-sm font-mono">{displayData.created_at_formatted}</p>
                  </div>
                  <Calendar className="w-4 h-4 text-muted-foreground/30" />
                </div>
                <Separator className="opacity-50" />
                <div className="flex items-center justify-between">
                  <div className="flex flex-col gap-1">
                    <span className="text-xs text-muted-foreground">آخر تحديث</span>
                    <p className="text-sm font-mono">{displayData.updated_at_formatted}</p>
                  </div>
                  <Clock className="w-4 h-4 text-muted-foreground/30" />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 左侧：状态中心与历史记录 */}
          <div className="lg:col-span-4 space-y-6">
            <Card className="overflow-hidden border-border bg-card shadow-lg ring-1 ring-primary/20">
              <CardHeader className="bg-primary/10 border-b border-primary/20 py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <CheckCircle2 className="w-4 h-4 text-primary" />
                  مركز التحكم بالحالة
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-6">
                <div className="flex flex-col items-center gap-3 p-4 bg-muted/20 rounded-lg border border-border">
                  <span className="text-xs text-muted-foreground font-header">الحالة الحالية للطلب</span>
                  <Badge className={`px-4 py-1.5 text-sm font-bold shadow-sm ${getStatusColor(displayData.status)}`}>
                    {STATUS_LABELS[displayData.status as keyof typeof STATUS_LABELS]}
                  </Badge>
                </div>

                {/* 动态操作按钮 */}
                {(displayData.status === 'PENDING' || displayData.status === 'IN_PROGRESS') && (
                  <div className="grid grid-cols-1 gap-2">
                    {displayData.status === 'PENDING' && (
                      <>
                        <Button 
                          onClick={() => handlers.openStatusChangeDialog('IN_PROGRESS')}
                          className="w-full bg-primary text-primary-foreground hover:shadow-neon-primary"
                        >
                          البدء بالتنفيذ
                        </Button>
                        <Button 
                          variant="outline" 
                          onClick={() => handlers.openStatusChangeDialog('CANCELLED')}
                          className="w-full border-destructive text-destructive hover:bg-destructive hover:text-destructive-foreground"
                        >
                          إلغاء الطلب
                        </Button>
                      </>
                    )}
                    {displayData.status === 'IN_PROGRESS' && (
                      <>
                        <Button 
                          onClick={() => handlers.openStatusChangeDialog('DELIVERED')}
                          className="w-full bg-accent text-accent-foreground hover:shadow-neon-accent"
                        >
                          تم التوصيل بنجاح
                        </Button>
                        <Button 
                          variant="outline" 
                          onClick={() => handlers.openStatusChangeDialog('CANCELLED')}
                          className="w-full border-destructive text-destructive hover:bg-destructive hover:text-destructive-foreground"
                        >
                          إلغاء الطلب
                        </Button>
                      </>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card className="overflow-hidden border-border bg-card shadow-md flex-1">
              <CardHeader className="bg-muted/30 border-b border-border py-4">
                <CardTitle className="text-sm font-header flex items-center gap-2">
                  <History className="w-4 h-4 text-primary" />
                  سجل الحالات
                </CardTitle>
              </CardHeader>
              <CardContent className="p-0">
                <ScrollArea className="h-[280px]">
                  <div className="p-6">
                    {displayData.histories.length === 0 ? (
                      <div className="text-center py-10">
                        <History className="w-8 h-8 text-muted-foreground/20 mx-auto mb-2" />
                        <p className="text-muted-foreground text-sm">لا يوجد سجل حركات لهذا الطلب</p>
                      </div>
                    ) : (
                      <div className="relative border-r-2 border-primary/20 pr-6 space-y-8">
                        {displayData.histories.map((history: any, idx: number) => (
                          <div key={history.history_id} className="relative">
                            <span className="absolute -right-[31px] top-1 w-2.5 h-2.5 rounded-full bg-primary shadow-neon-primary border-2 border-background" />
                            <div className="flex flex-col gap-1">
                              <time className="text-[10px] font-mono text-muted-foreground bg-muted w-fit px-1.5 rounded">
                                {history.created_at_formatted}
                              </time>
                              <div className="flex items-center gap-2 mt-1">
                                <span className="text-xs line-through text-muted-foreground/60">
                                  {history.from_status ? STATUS_LABELS[history.from_status as keyof typeof STATUS_LABELS] : 'جديد'}
                                </span>
                                <ArrowRight className="w-3 h-3 text-primary rotate-180" />
                                <span className="text-sm font-bold text-primary">
                                  {STATUS_LABELS[history.to_status as keyof typeof STATUS_LABELS]}
                                </span>
                              </div>
                              <p className="text-[11px] text-muted-foreground">المشغل: {history.changed_by_name || 'النظام'}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </ScrollArea>
              </CardContent>
            </Card>
          </div>

        </div>
      </section>

      {/* الحوارات - Dialogs */}
      
      {/* تأكيد الحذف */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={handlers.setIsDeleteDialogOpen}>
        <DialogContent className="sm:max-w-[425px] border-destructive/20 bg-card overflow-auto max-h-full">
          <DialogHeader className="text-right">
            <DialogTitle className="flex items-center gap-2 text-destructive font-header">
              <Trash2 className="w-5 h-5" />
              تأكيد الحذف النهائي
            </DialogTitle>
            <DialogDescription className="text-muted-foreground pt-2">
              هل أنت متأكد من رغبتك في حذف هذا الطلب بشكل نهائي؟ سيتم مسح كافة البيانات وسجل الحالات المرتبط به، ولا يمكن التراجع عن هذا الإجراء.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-row-reverse gap-2 sm:justify-start pt-4">
            <Button 
              variant="outline" 
              onClick={() => handlers.setIsDeleteDialogOpen(false)} 
              disabled={isDeleting}
              className="flex-1"
            >
              تراجع
            </Button>
            <Button 
              variant="destructive" 
              onClick={handlers.confirmDelete} 
              disabled={isDeleting}
              className="flex-1 bg-destructive text-destructive-foreground hover:shadow-lg"
            >
              {isDeleting ? 'جاري المسح...' : 'نعم، حذف الطلب'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* تغيير الحالة */}
      <Dialog 
        open={statusChangeDialog.isOpen} 
        onOpenChange={(open) => !open && handlers.setStatusChangeDialog({ isOpen: false, targetStatus: null })}
      >
        <DialogContent className="sm:max-w-[425px] border-primary/20 bg-card overflow-auto max-h-full">
          <DialogHeader className="text-right">
            <DialogTitle className="flex items-center gap-2 text-primary font-header">
              <CheckCircle2 className="w-5 h-5" />
              تحديث حالة الطلب
            </DialogTitle>
            <DialogDescription className="text-muted-foreground pt-2 leading-relaxed">
              أنت على وشك تغيير حالة الطلب الحالية إلى 
              <span className="mx-1 font-bold text-foreground underline underline-offset-4 decoration-primary">
                &quot;{statusChangeDialog.targetStatus && STATUS_LABELS[statusChangeDialog.targetStatus]}&quot;
              </span>. 
              هل ترغب في المتابعة؟
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-row-reverse gap-2 sm:justify-start pt-4">
            <Button 
              variant="outline" 
              onClick={() => handlers.setStatusChangeDialog({ isOpen: false, targetStatus: null })} 
              disabled={isChangingStatus}
              className="flex-1"
            >
              إلغاء
            </Button>
            <Button 
              onClick={handlers.confirmStatusChange} 
              disabled={isChangingStatus}
              className="flex-1 bg-primary text-primary-foreground hover:shadow-neon-primary"
            >
              {isChangingStatus ? 'جاري التحديث...' : 'تأكيد التغيير'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </main>
  );
};
