'use client'

import React from 'react'
import { 
  Search, 
  RefreshCcw, 
  BarChart3, 
  Download, 
  Eye, 
  Pencil, 
  Trash2, 
  ChevronRight, 
  ChevronLeft, 
  ChevronsRight, 
  ChevronsLeft,
  AlertCircle
} from 'lucide-react'
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import type { OrderManagementState, OrderManagementHandlers } from '@/backend/hooks/useOrderManagement'

interface Props {
  state: OrderManagementState
  handlers: OrderManagementHandlers
}

export const OrderManagementView = ({ state, handlers }: Props) => {
  return (
    <div className="min-h-screen bg-background text-foreground font-body dir-rtl" dir="rtl">
      
      {/* 1. Page Header */}
      <section className="w-full border-b border-border bg-card/30 backdrop-blur-md sticky top-0 z-30" data-controller-name="ترويسة إدارة الطلبات">
        <div className="container mx-auto px-8 py-4 flex flex-col md:flex-row justify-between items-center gap-4">
          <div className="flex flex-col">
            <h1 className="text-2xl font-display font-bold text-primary-foreground tracking-tight">إدارة الطلبات</h1>
            <p className="text-xs text-muted-foreground font-header mt-1">نظام تتبع ومعالجة الشحنات اللوجستية</p>
          </div>
          
          <div className="flex flex-wrap items-center gap-2">
            <Button 
              variant="secondary" 
              size="sm" 
              onClick={() => handlers.fetchData()}
              className="hover:shadow-neon-primary transition-all duration-300"
            >
              <RefreshCcw className="w-4 h-4 ml-2" />
              تحديث البيانات
            </Button>
            
            <Separator orientation="vertical" className="h-8 mx-1 hidden md:block" />
            
            <div className="flex gap-2">
              <Button variant="outline" size="sm" onClick={() => handlers.navigateToAnalytics('default')}>
                <BarChart3 className="w-4 h-4 ml-2 text-meshwar-orange" />
                الإحصائيات
              </Button>
              <Button variant="outline" size="sm" onClick={() => handlers.navigateToExport('orders')}>
                <Download className="w-4 h-4 ml-2" />
                تصدير السجلات
              </Button>
            </div>
          </div>
        </div>
      </section>

      {/* 2. Summary Dashboard */}
      <section className="w-full bg-gradient-hero-bg" data-controller-name="ملخص مؤشرات الأداء">
        <div className="container mx-auto px-8 py-8">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
            {/* Total Card */}
            <KPIItem 
              label="إجمالي الطلبات" 
              value={state.summary?.total_count || 0} 
              variant="default" 
            />
            {/* Pending Card */}
            <KPIItem 
              label="قيد الانتظار" 
              value={state.summary?.pending_count || 0} 
              variant="pending" 
              onClick={() => handlers.handleKPIStatusClick('PENDING')}
            />
            {/* In Progress Card */}
            <KPIItem 
              label="قيد التوصيل" 
              value={state.summary?.in_progress_count || 0} 
              variant="in_progress" 
              onClick={() => handlers.handleKPIStatusClick('IN_PROGRESS')}
            />
            {/* Delivered Card */}
            <KPIItem 
              label="تم التوصيل" 
              value={state.summary?.delivered_count || 0} 
              variant="delivered" 
              onClick={() => handlers.handleKPIStatusClick('DELIVERED')}
            />
            {/* Cancelled Card */}
            <KPIItem 
              label="ملغى" 
              value={state.summary?.cancelled_count || 0} 
              variant="cancelled" 
              onClick={() => handlers.handleKPIStatusClick('CANCELLED')}
            />
          </div>
        </div>
      </section>

      {/* 3. Filter & Search Panel */}
      <section className="w-full" data-controller-name="لوحة التحكم والتصفية">
        <div className="container mx-auto px-8 py-4">
          <Card className="border-border/50 shadow-md bg-card/50 overflow-hidden">
            <CardContent className="p-6">
              <div className="space-y-6">
                {/* Search Bar */}
                <div className="flex flex-col md:flex-row gap-3">
                  <div className="relative flex-grow">
                    <Input 
                      className="h-11 pr-4 bg-background border-border focus:ring-primary shadow-sm"
                      placeholder="البحث برقم الطلب، اسم الزبون، أو رقم الهاتف..." 
                      value={state.filterForm.keyword}
                      onChange={(e) => handlers.handleFormFieldChange('keyword', e.target.value)}
                    />
                  </div>
                  <Button 
                    className="h-11 px-8 bg-meshwar-brand hover:bg-meshwar-brand/90 text-primary-foreground shadow-neon-primary"
                    onClick={handlers.handleApplySearch}
                  >
                    <Search className="w-4 h-4 ml-2" />
                    بحث سريع
                  </Button>
                </div>

                <Separator className="bg-border/30" />

                {/* Filters Grid */}
                <form 
                  onSubmit={(e) => { e.preventDefault(); handlers.handleApplyFilters(); }}
                  className="flex flex-wrap items-end gap-4"
                >
                  <FilterGroup label="المحافظة">
                    <Select 
                      value={state.filterForm.governorateName || 'ALL'} 
                      onValueChange={(val) => handlers.handleFormFieldChange('governorateName', val === 'ALL' ? '' : val)}
                    >
                      <SelectTrigger className="h-10 w-[180px] bg-background">
                        <SelectValue placeholder="اختر المحافظة" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ALL">جميع المحافظات</SelectItem>
                        {state.filterOptions.governorates.map(gov => (
                          <SelectItem key={gov} value={gov}>{gov}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FilterGroup>

                  <FilterGroup label="اسم السائق">
                    <Select 
                      value={state.filterForm.driverName || 'ALL'} 
                      onValueChange={(val) => handlers.handleFormFieldChange('driverName', val === 'ALL' ? '' : val)}
                    >
                      <SelectTrigger className="h-10 w-[180px] bg-background">
                        <SelectValue placeholder="اختر السائق" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ALL">جميع السائقين</SelectItem>
                        {state.filterOptions.drivers.map(driver => (
                          <SelectItem key={driver} value={driver}>{driver}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FilterGroup>

                  <FilterGroup label="نوع الطلب">
                    <Select 
                      value={state.filterForm.orderType || 'ALL'} 
                      onValueChange={(val) => handlers.handleFormFieldChange('orderType', val === 'ALL' ? '' : val)}
                    >
                      <SelectTrigger className="h-10 w-[140px] bg-background">
                        <SelectValue placeholder="النوع" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ALL">الكل</SelectItem>
                        {state.filterOptions.order_types.map(type => (
                          <SelectItem key={type} value={type}>{type}</SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </FilterGroup>

                  <FilterGroup label="حالة الطلب">
                    <Select 
                      value={state.filterForm.status || 'ALL'} 
                      onValueChange={(val) => handlers.handleFormFieldChange('status', val === 'ALL' ? '' : val)}
                    >
                      <SelectTrigger className="h-10 w-[140px] bg-background">
                        <SelectValue placeholder="الحالة" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ALL">جميع الحالات</SelectItem>
                        <SelectItem value="PENDING">قيد الانتظار</SelectItem>
                        <SelectItem value="IN_PROGRESS">قيد التوصيل</SelectItem>
                        <SelectItem value="DELIVERED">تم التوصيل</SelectItem>
                        <SelectItem value="CANCELLED">ملغى</SelectItem>
                      </SelectContent>
                    </Select>
                  </FilterGroup>

                  <FilterGroup label="من تاريخ">
                    <Input 
                      type="date" 
                      className="h-10 w-[160px] bg-background px-3"
                      value={state.filterForm.startDate} 
                      onChange={(e) => handlers.handleFormFieldChange('startDate', e.target.value)}
                    />
                  </FilterGroup>

                  <FilterGroup label="إلى تاريخ">
                    <Input 
                      type="date" 
                      className="h-10 w-[160px] bg-background px-3"
                      value={state.filterForm.endDate} 
                      onChange={(e) => handlers.handleFormFieldChange('endDate', e.target.value)}
                    />
                  </FilterGroup>

                  <div className="flex gap-2 flex-shrink-0 pt-6">
                    <Button type="submit" className="h-10 bg-secondary text-secondary-foreground hover:bg-secondary/80">
                      تطبيق الفلاتر
                    </Button>
                    <Button type="button" variant="ghost" onClick={handlers.handleResetFilters} className="h-10 text-muted-foreground">
                      إعادة ضبط
                    </Button>
                  </div>
                </form>
              </div>
            </CardContent>
          </Card>
        </div>
      </section>

      {/* 4. Main Data Table */}
      <section className="w-full" data-controller-name="جدول بيانات الطلبات">
        <div className="container mx-auto px-8 pb-8">
          <Card className="border-border/50 shadow-lg bg-card overflow-hidden">
            <div className="relative overflow-x-auto">
              <Table className="font-body">
                <TableHeader className="bg-muted/50 border-b border-border">
                  <TableRow className="hover:bg-transparent">
                    <TableHead className="w-[120px] font-bold text-foreground">رقم الطلب</TableHead>
                    <TableHead className="font-bold text-foreground">الزبون</TableHead>
                    <TableHead className="font-bold text-foreground">رقم الهاتف</TableHead>
                    <TableHead className="font-bold text-foreground">الموقع</TableHead>
                    <TableHead className="font-bold text-foreground">السائق</TableHead>
                    <TableHead className="font-bold text-foreground text-center">النوع</TableHead>
                    <TableHead className="font-bold text-foreground text-center">الحالة</TableHead>
                    <TableHead className="font-bold text-foreground">تاريخ الإنشاء</TableHead>
                    <TableHead className="font-bold text-foreground text-left sticky left-0 bg-muted/80 backdrop-blur-sm shadow-[-4px_0_8px_rgba(0,0,0,0.1)]">الإجراءات</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {state.isLoading ? (
                    <TableRow>
                      <TableCell colSpan={9} className="h-64 text-center">
                        <div className="flex flex-col items-center justify-center space-y-3">
                          <RefreshCcw className="w-8 h-8 animate-spin text-primary" />
                          <span className="text-muted-foreground">جاري استخراج البيانات...</span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : state.list.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={9} className="h-64 text-center">
                        <div className="flex flex-col items-center justify-center space-y-2">
                          <AlertCircle className="w-12 h-12 text-muted/30" />
                          <p className="text-lg font-header text-muted-foreground">لا توجد نتائج مطابقة لخيارات البحث</p>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    state.list.map((order) => (
                      <TableRow key={order.order_id} className="hover:bg-muted/20 border-border/40 transition-colors">
                        <TableCell className="font-mono text-xs font-semibold">{order.order_no}</TableCell>
                        <TableCell className="font-header text-sm">{order.customer_name}</TableCell>
                        <TableCell className="font-mono text-xs">{order.customer_phone}</TableCell>
                        <TableCell>
                          <div className="flex flex-col">
                            <span className="text-sm font-medium">{order.governorate_name}</span>
                            <span className="text-[10px] text-muted-foreground">{order.area_name}</span>
                          </div>
                        </TableCell>
                        <TableCell className="text-sm">{order.driver_name || '—'}</TableCell>
                        <TableCell className="text-center">
                          <span className="text-xs px-2 py-1 rounded bg-muted text-muted-foreground">{order.order_type}</span>
                        </TableCell>
                        <TableCell className="text-center">
                          <StatusBadge status={order.status} label={state.statusLabels[order.status]} />
                        </TableCell>
                        <TableCell className="text-[11px] text-muted-foreground">
                          {new Date(order.created_at).toLocaleString('ar-IQ', {
                            dateStyle: 'medium',
                            timeStyle: 'short'
                          })}
                        </TableCell>
                        <TableCell className="sticky left-0 bg-card/95 backdrop-blur-sm shadow-[-4px_0_8px_rgba(0,0,0,0.1)]">
                          <div className="flex items-center gap-1 justify-end">
                            <Button 
                              variant="ghost" 
                              size="icon" 
                              className="h-8 w-8 text-primary hover:bg-primary/10"
                              onClick={() => handlers.navigateToDetail(order.order_id)}
                            >
                              <Eye className="w-4 h-4" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="icon" 
                              className="h-8 w-8 text-accent hover:bg-accent/10"
                              onClick={() => handlers.navigateToEdit(order.order_id)}
                            >
                              <Pencil className="w-4 h-4" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="icon" 
                              className="h-8 w-8 text-destructive hover:bg-destructive/10"
                              onClick={() => {
                                handlers.setOrderToDelete(order);
                                handlers.setDeleteModalOpen(true);
                              }}
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            {/* Pagination & Footer Bar */}
            <div className="border-t border-border bg-muted/30 px-6 py-4 flex flex-col sm:flex-row justify-between items-center gap-4">
              <div className="flex items-center gap-4">
                <span className="text-sm text-muted-foreground">
                  عرض <span className="text-foreground font-semibold">{(state.filterForm.page - 1) * state.filterForm.pageSize + 1} - {Math.min(state.filterForm.page * state.filterForm.pageSize, state.total)}</span> من <span className="text-foreground font-semibold">{state.total}</span> طلب
                </span>
                
                <div className="flex items-center gap-2">
                  <span className="text-xs text-muted-foreground">سجل / صفحة:</span>
                  <Select 
                    value={state.filterForm.pageSize.toString()} 
                    onValueChange={(val) => handlers.handleFormFieldChange('pageSize', parseInt(val, 10))}
                  >
                    <SelectTrigger className="h-8 w-16 bg-background text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="20">20</SelectItem>
                      <SelectItem value="50">50</SelectItem>
                      <SelectItem value="100">100</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="flex items-center gap-1">
                <PaginationButton 
                  onClick={() => handlers.handlePageChange(1)} 
                  disabled={state.filterForm.page <= 1}
                  icon={<ChevronsRight className="w-4 h-4" />}
                />
                <PaginationButton 
                  onClick={() => handlers.handlePageChange(state.filterForm.page - 1)} 
                  disabled={state.filterForm.page <= 1}
                  icon={<ChevronRight className="w-4 h-4" />}
                />
                
                <div className="flex items-center px-4 h-8 rounded border border-border bg-background text-xs font-semibold">
                  صفحة {state.filterForm.page} من {state.totalPages}
                </div>

                <PaginationButton 
                  onClick={() => handlers.handlePageChange(state.filterForm.page + 1)} 
                  disabled={state.filterForm.page >= state.totalPages}
                  icon={<ChevronLeft className="w-4 h-4" />}
                />
                <PaginationButton 
                  onClick={() => handlers.handlePageChange(state.totalPages)} 
                  disabled={state.filterForm.page >= state.totalPages}
                  icon={<ChevronsLeft className="w-4 h-4" />}
                />
              </div>
            </div>
          </Card>
        </div>
      </section>

      {/* Delete Confirmation Modal */}
      <Dialog open={state.deleteModalOpen} onOpenChange={handlers.setDeleteModalOpen}>
        <DialogContent className="max-w-md bg-popover border-border">
          <DialogHeader className="space-y-3">
            <div className="mx-auto w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center">
              <Trash2 className="w-6 h-6 text-destructive" />
            </div>
            <DialogTitle className="text-center text-xl font-header">تأكيد حذف الطلب</DialogTitle>
            <DialogDescription className="text-center text-muted-foreground">
              هل أنت متأكد من رغبتك في حذف الطلب رقم <span className="text-foreground font-mono font-bold">"{state.orderToDelete?.order_no}"</span>؟
              <br />
              هذا الإجراء نهائي وسوف يؤدي إلى إزالة جميع البيانات المرتبطة بهذا السجل.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex sm:flex-row flex-col gap-2 mt-4">
            <Button variant="outline" className="flex-1" onClick={() => handlers.setDeleteModalOpen(false)}>
              إلغاء الأمر
            </Button>
            <Button variant="destructive" className="flex-1 shadow-md" onClick={handlers.handleDeleteConfirm}>
              تأكيد الحذف النهائي
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

/**
 * Helper Components
 */

const KPIItem = ({ 
  label, 
  value, 
  variant = 'default', 
  onClick 
}: { 
  label: string; 
  value: number; 
  variant?: 'default' | 'pending' | 'in_progress' | 'delivered' | 'cancelled'; 
  onClick?: () => void 
}) => {
  const styles = {
    default: "border-primary/20 bg-primary/5",
    pending: "border-muted-foreground/20 bg-muted/5",
    in_progress: "border-blue-500/20 bg-blue-500/5",
    delivered: "border-green-500/20 bg-green-500/5",
    cancelled: "border-destructive/20 bg-destructive/5"
  }

  const textColors = {
    default: "text-primary",
    pending: "text-muted-foreground",
    in_progress: "text-blue-400",
    delivered: "text-green-400",
    cancelled: "text-destructive"
  }

  return (
    <Card 
      className={`border-2 ${styles[variant]} transition-all duration-300 hover:shadow-neon-primary cursor-pointer group`}
      onClick={onClick}
    >
      <CardContent className="p-4 text-center">
        <p className="text-xs font-header text-muted-foreground uppercase tracking-wider mb-1">{label}</p>
        <p className={`text-2xl font-display font-bold ${textColors[variant]} group-hover:scale-110 transition-transform`}>
          {value.toLocaleString()}
        </p>
      </CardContent>
    </Card>
  )
}

const FilterGroup = ({ label, children }: { label: string; children: React.ReactNode }) => (
  <div className="flex flex-col gap-1.5">
    <label className="text-xs font-header text-muted-foreground mr-1">{label}</label>
    {children}
  </div>
)

const StatusBadge = ({ status, label }: { status: string; label: string }) => {
  const variants: Record<string, string> = {
    PENDING: "bg-muted text-muted-foreground border-transparent",
    IN_PROGRESS: "bg-blue-500/10 text-blue-400 border-blue-500/20",
    DELIVERED: "bg-green-500/10 text-green-400 border-green-500/20",
    CANCELLED: "bg-destructive/10 text-destructive border-destructive/20"
  }
  
  return (
    <Badge variant="outline" className={`px-2 py-0.5 font-header text-[10px] whitespace-nowrap ${variants[status] || variants.PENDING}`}>
      {label}
    </Badge>
  )
}

const PaginationButton = ({ onClick, disabled, icon }: { onClick: () => void; disabled: boolean; icon: React.ReactNode }) => (
  <Button 
    variant="ghost" 
    size="icon" 
    className="h-8 w-8 hover:bg-muted"
    onClick={onClick} 
    disabled={disabled}
  >
    {icon}
  </Button>
)
