'use client';

import React from 'react';
import type { ReportExportState, ReportExportHandlers } from '@/backend/hooks/useReportExport';
import type { ReportType, DeliveryOrderStatus } from '@/backend/actions/ReportExport';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Card, CardContent } from "@/components/ui/card";
import { FileSpreadsheet, FileText, LayoutDashboard, Loader2, SearchX, CalendarDays, MapPin, User, Filter } from "lucide-react";
import { cn } from "@/lib/utils";

const formatCurrency = (amount: number) => new Intl.NumberFormat('ar-IQ', {
  style: 'currency',
  currency: 'IQD',
  maximumFractionDigits: 0
}).format(amount);

type OrderPreviewItem = NonNullable<ReportExportState['reportData']['orders']>[number] & {
  totalAmount: number;
};

interface Props {
  state: ReportExportState;
  handlers: ReportExportHandlers;
}
export const ReportExportView = ({
  state,
  handlers
}: Props) => {
  return <div className="min-h-screen bg-background text-foreground font-body dir-rtl bg-[url('https://www.transparenttextures.com/patterns/dark-matter.png')]">
      
      {/* HEADER SECTION */}
      <section data-controller-name="رأس الصفحة والتحكم" className="w-full border-b border-border bg-card/50 backdrop-blur-md sticky top-0 z-50">
        <div className="container mx-auto px-8 py-6 flex flex-col md:flex-row justify-between items-center gap-6">
          <div className="space-y-1">
            <h1 className="text-3xl font-display font-bold text-primary-foreground drop-shadow-neon-primary">
              تصدير التقارير
            </h1>
            <p className="text-muted-foreground text-sm font-header">
              إدارة وتحميل تقارير العمليات اللوجستية بدقة عالية
            </p>
          </div>
          
          <div className="flex items-center gap-4">
            <Button onClick={handlers.handleGoToAnalytics} variant="outline" className="border-primary/40 hover:bg-primary hover:text-primary-foreground transition-all duration-300">
              <LayoutDashboard className="ml-2 h-4 w-4" />
              <span>الذهاب للإحصائيات الشهرية</span>
            </Button>
          </div>
        </div>
      </section>

      <main className="container mx-auto px-8 py-8 space-y-8">
        
        {/* REPORT TYPE SELECTOR */}
        <section data-controller-name="تحديد نوع التقرير" className="flex justify-center">
          <Card className="bg-secondary/30 border-primary/20 p-1 rounded-xl shadow-md inline-block">
            <ToggleGroup type="single" value={state.reportType} onValueChange={val => val && handlers.setReportType(val as ReportType)} className="flex gap-1">
              <ToggleGroupItem value="ORDERS" className="px-8 py-2 rounded-lg data-[state=on]:bg-primary data-[state=on]:text-primary-foreground transition-all font-header">
                {state.REPORT_TYPE_LABELS['ORDERS']}
              </ToggleGroupItem>
              <ToggleGroupItem value="DRIVERS" className="px-8 py-2 rounded-lg data-[state=on]:bg-primary data-[state=on]:text-primary-foreground transition-all font-header">
                {state.REPORT_TYPE_LABELS['DRIVERS']}
              </ToggleGroupItem>
              <ToggleGroupItem value="GOVERNORATES" className="px-8 py-2 rounded-lg data-[state=on]:bg-primary data-[state=on]:text-primary-foreground transition-all font-header">
                {state.REPORT_TYPE_LABELS['GOVERNORATES']}
              </ToggleGroupItem>
            </ToggleGroup>
          </Card>
        </section>

        {/* FILTERS MODULE */}
        <section data-controller-name="مرشحات البحث" className="w-full">
          <Card className="bg-card border-border shadow-lg overflow-hidden">
            <div className="bg-muted/50 px-6 py-3 border-b border-border flex items-center gap-2">
              <Filter className="h-4 w-4 text-primary" />
              <span className="text-sm font-header font-semibold">تخصيص البيانات</span>
            </div>
            <CardContent className="p-6">
              <div className="flex flex-wrap gap-6 items-end">
                {/* Start Date */}
                <div className="flex-1 min-w-[180px] space-y-2">
                  <label className="text-xs font-header text-muted-foreground flex items-center gap-1">
                    <CalendarDays className="h-3 w-3" /> من تاريخ
                  </label>
                  <Input type="date" value={state.startDate} onChange={e => handlers.setStartDate(e.target.value)} className="h-11 bg-input px-4 focus:ring-primary/50" />
                </div>

                {/* End Date */}
                <div className="flex-1 min-w-[180px] space-y-2">
                  <label className="text-xs font-header text-muted-foreground flex items-center gap-1">
                    <CalendarDays className="h-3 w-3" /> إلى تاريخ
                  </label>
                  <Input type="date" value={state.endDate} onChange={e => handlers.setEndDate(e.target.value)} className="h-11 bg-input px-4 focus:ring-primary/50" />
                </div>

                {/* Governorate */}
                <div className="flex-1 min-w-[180px] space-y-2">
                  <label className="text-xs font-header text-muted-foreground flex items-center gap-1">
                    <MapPin className="h-3 w-3" /> المحافظة
                  </label>
                  <Input value={state.localGovernorateName} onChange={e => handlers.handleGovChange(e.target.value)} onCompositionStart={handlers.handleGovCompositionStart} onCompositionEnd={handlers.handleGovCompositionEnd} placeholder="بحث باسم المحافظة" className="h-11 bg-input px-4 focus:ring-primary/50" />
                </div>

                {/* Driver */}
                <div className="flex-1 min-w-[180px] space-y-2">
                  <label className="text-xs font-header text-muted-foreground flex items-center gap-1">
                    <User className="h-3 w-3" /> اسم السائق
                  </label>
                  <Input value={state.localDriverName} onChange={e => handlers.handleDriverChange(e.target.value)} onCompositionStart={handlers.handleDriverCompositionStart} onCompositionEnd={handlers.handleDriverCompositionEnd} placeholder="بحث باسم السائق" className="h-11 bg-input px-4 focus:ring-primary/50" />
                </div>

                {/* Order Status */}
                <div className="flex-1 min-w-[180px] space-y-2">
                  <label className="text-xs font-header text-muted-foreground">حالة الطلب</label>
                  <Select value={state.status} onValueChange={val => handlers.setStatus(val as DeliveryOrderStatus | '')}>
                    <SelectTrigger className="h-11 bg-input px-4 border-border">
                      <SelectValue placeholder="الكل" />
                    </SelectTrigger>
                    <SelectContent className="bg-popover border-border rounded-none">
                      <SelectItem value="" className="rounded-none">الكل</SelectItem>
                      <SelectItem value="PENDING" className="rounded-none">{state.STATUS_LABELS['PENDING']}</SelectItem>
                      <SelectItem value="IN_PROGRESS" className="rounded-none">{state.STATUS_LABELS['IN_PROGRESS']}</SelectItem>
                      <SelectItem value="DELIVERED" className="rounded-none">{state.STATUS_LABELS['DELIVERED']}</SelectItem>
                      <SelectItem value="CANCELLED" className="rounded-none">{state.STATUS_LABELS['CANCELLED']}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        </section>

        {/* PREVIEW DISPLAY */}
        <section data-controller-name="معاينة البيانات" className="w-full">
          <Card className="bg-card border-border shadow-lg min-h-[400px] flex flex-col relative overflow-hidden">
            <div className="px-6 py-4 border-b border-border bg-muted/20 flex justify-between items-center">
              <h3 className="font-header font-bold text-lg">معاينة البيانات</h3>
              <span className="text-xs text-muted-foreground bg-secondary px-3 py-1 rounded-full">
                يعرض أول 50 سجلاً فقط
              </span>
            </div>

            <CardContent className="flex-1 p-0 overflow-auto max-h-[600px]">
              {state.isLoading ? <div className="h-full w-full flex flex-col items-center justify-center space-y-4 py-20">
                  <Loader2 className="h-12 w-12 text-primary animate-spin" />
                  <p className="text-muted-foreground animate-pulse font-header">جاري استرجاع البيانات المحدثة...</p>
                </div> : !state.hasData ? <div className="h-full w-full flex flex-col items-center justify-center space-y-4 py-20 opacity-60">
                  <SearchX className="h-16 w-16 text-muted-foreground" />
                  <p className="text-xl font-header font-medium">لا توجد نتائج مطابقة</p>
                  <p className="text-sm text-muted-foreground">جرب تغيير مرشحات البحث للحصول على بيانات</p>
                </div> : <div className="w-full">
                  {state.reportType === 'ORDERS' && <Table>
                      <TableHeader className="bg-muted/50 sticky top-0 z-10">
                        <TableRow className="border-border">
                          <TableHead className="text-primary font-bold">رقم الطلب</TableHead>
                          <TableHead>المحافظة</TableHead>
                          <TableHead>اسم العميل</TableHead>
                          <TableHead>اسم السائق</TableHead>
                          <TableHead>المبلغ الكلي</TableHead>
                          <TableHead>الحالة</TableHead>
                          <TableHead className="text-left">تاريخ الإنشاء</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {state.reportData.orders?.slice(0, 50).map(order => {
                          const orderItem = order as OrderPreviewItem;
                          return <TableRow key={orderItem.order_id} className="hover:bg-primary/5 transition-colors border-border">
                            <TableCell className="font-mono font-medium text-primary-foreground">{orderItem.order_no}</TableCell>
                            <TableCell>{orderItem.governorate_name}</TableCell>
                            <TableCell>{orderItem.customer_name}</TableCell>
                            <TableCell>{orderItem.driver_name}</TableCell>
                            <TableCell className="font-mono whitespace-nowrap">{formatCurrency(orderItem.totalAmount)}</TableCell>
                            <TableCell>
                              <span className={cn("px-2 py-1 rounded-sm text-[10px] font-bold uppercase", orderItem.status === 'DELIVERED' ? "bg-green-500/20 text-green-400" : orderItem.status === 'CANCELLED' ? "bg-destructive/20 text-destructive" : "bg-primary/20 text-primary-foreground")}>
                                {state.STATUS_LABELS[orderItem.status]}
                              </span>
                            </TableCell>
                            <TableCell className="text-left text-muted-foreground text-xs">
                              {new Date(orderItem.created_at).toLocaleDateString('ar-IQ')}
                            </TableCell>
                          </TableRow>})}
                      </TableBody>
                    </Table>}

                  {state.reportType === 'DRIVERS' && <Table>
                      <TableHeader className="bg-muted/50 sticky top-0 z-10">
                        <TableRow className="border-border">
                          <TableHead className="text-primary font-bold">اسم السائق</TableHead>
                          <TableHead>إجمالي الطلبات</TableHead>
                          <TableHead>قيد الانتظار</TableHead>
                          <TableHead>تم التوصيل</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {state.reportData.drivers?.map((driver, index) => <TableRow key={index} className="hover:bg-primary/5 transition-colors border-border">
                            <TableCell className="font-header font-medium">{driver.driver_name}</TableCell>
                            <TableCell className="font-mono">{driver.total_orders}</TableCell>
                            <TableCell className="text-amber-400">{driver.pending_orders}</TableCell>
                            <TableCell className="text-green-400">{driver.delivered_orders}</TableCell>
                          </TableRow>)}
                      </TableBody>
                    </Table>}

                  {state.reportType === 'GOVERNORATES' && <Table>
                      <TableHeader className="bg-muted/50 sticky top-0 z-10">
                        <TableRow className="border-border">
                          <TableHead className="text-primary font-bold">المحافظة</TableHead>
                          <TableHead>إجمالي الطلبات</TableHead>
                          <TableHead>قيد الانتظار</TableHead>
                          <TableHead>تم التوصيل</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {state.reportData.governorates?.map((gov, index) => <TableRow key={index} className="hover:bg-primary/5 transition-colors border-border">
                            <TableCell className="font-header font-medium">{gov.governorate_name}</TableCell>
                            <TableCell className="font-mono">{gov.total_orders}</TableCell>
                            <TableCell className="text-amber-400">{gov.pending_orders}</TableCell>
                            <TableCell className="text-green-400">{gov.delivered_orders}</TableCell>
                          </TableRow>)}
                      </TableBody>
                    </Table>}
                </div>}
            </CardContent>
          </Card>
        </section>

        {/* FINAL ACTIONS BAR */}
        <section data-controller-name="إجراءات التصدير النهائية" className="flex justify-center md:justify-end">
          <Card className="bg-card border-border p-4 shadow-xl flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
            <div className="text-sm text-muted-foreground ml-4 text-center md:text-right">
              هل أنت جاهز؟ سيتم تصدير كافة السجلات بناءً على الفلاتر المختارة
            </div>
            <div className="flex gap-3 w-full md:w-auto">
              <Button onClick={handlers.handleExportCSV} disabled={!state.hasData || state.isLoading} variant="secondary" className="flex-1 md:flex-none h-12 px-6 font-header border border-border hover:bg-muted transition-all">
                <FileSpreadsheet className="ml-2 h-5 w-5 text-green-500" />
                تصدير Excel (CSV)
              </Button>
              <Button onClick={handlers.handleExportPDF} disabled={!state.hasData || state.isLoading} className="flex-1 md:flex-none h-12 px-8 font-header bg-accent text-accent-foreground shadow-neon-accent hover:opacity-90 transition-all">
                <FileText className="ml-2 h-5 w-5" />
                تصدير PDF
              </Button>
            </div>
          </Card>
        </section>
      </main>

      {/* FOOTER SPACE */}
      <footer className="w-full py-12 border-t border-border mt-12 bg-muted/10">
        <div className="container mx-auto px-8 text-center text-muted-foreground text-sm">
          <p>© {new Date().getFullYear()} Meshwar Premium Logistics - نظام إدارة التقارير الذكي</p>
        </div>
      </footer>
    </div>;
};
