import React, { useState } from 'react';
import { 
  Search, 
  Download, 
  Printer,
  Calendar,
  Filter,
  BarChart3,
  PieChart,
  LineChart,
  ArrowUpRight,
  RefreshCw,
  FileText
} from 'lucide-react';
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "../ui/card";
import { Badge } from "../ui/badge";
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  Legend, 
  ResponsiveContainer,
  Line,
  LineChart as RechartsLineChart 
} from 'recharts';
import { toast } from "sonner@2.0.3";
import { cn } from "../ui/utils";

// --- Mock Data ---

const MOCK_PRINT_LOG = [
  { 
    id: '1-251201', 
    productName: 'Whole Milk', 
    category: 'Dairy', 
    template: '2"x2" Basic',
    printedAt: '2024-03-20 09:30 AM', 
    printedBy: 'Alice Johnson', 
    location: 'Downtown Store (101)',
    expiryDate: '2024-03-27',
    status: 'Valid' 
  },
  { 
    id: '2-251201', 
    productName: 'Ground Beef', 
    category: 'Meat', 
    template: '2"x2" Basic',
    printedAt: '2024-03-20 10:15 AM', 
    printedBy: 'Bob Smith', 
    location: 'Uptown Store (102)',
    expiryDate: '2024-03-23',
    status: 'Valid' 
  },
  { 
    id: '3-251201', 
    productName: 'Croissant', 
    category: 'Bakery', 
    template: '2"x2" Basic',
    printedAt: '2024-03-19 14:00 PM', 
    printedBy: 'Charlie Brown', 
    location: 'Downtown Store (101)',
    expiryDate: '2024-03-20',
    status: 'Expired' 
  },
  { 
    id: '4-251201', 
    productName: 'Caesar Salad', 
    category: 'Deli', 
    template: '2"x6" G\'n\'G !!!',
    printedAt: '2024-03-18 11:45 AM', 
    printedBy: 'Alice Johnson', 
    location: 'Downtown Store (101)',
    expiryDate: '2024-03-21',
    status: 'Expiring Soon' 
  },
  { 
    id: '5-251201', 
    productName: 'Orange Juice', 
    category: 'Beverage', 
    template: '2"x2" Basic',
    printedAt: '2024-03-18 08:20 AM', 
    printedBy: 'Bob Smith', 
    location: 'Airport Kiosk (201)',
    expiryDate: '2024-03-25',
    status: 'Valid' 
  },
];

const MOCK_CATEGORY_STATS = [
  { name: 'Dairy', count: 450 },
  { name: 'Meat', count: 320 },
  { name: 'Bakery', count: 280 },
  { name: 'Deli', count: 190 },
  { name: 'Produce', count: 150 },
  { name: 'Beverage', count: 120 },
];

const MOCK_USAGE_TRENDS = [
  { date: 'Mon', count: 120 },
  { date: 'Tue', count: 132 },
  { date: 'Wed', count: 101 },
  { date: 'Thu', count: 134 },
  { date: 'Fri', count: 190 },
  { date: 'Sat', count: 230 },
  { date: 'Sun', count: 210 },
];

export function ReportsView() {
  const [activeTab, setActiveTab] = useState('print-log');

  const handleReprint = (labelId: string) => {
    // Logic to reprint would go here
    // For now, we simulate the action
    toast.success(`Reprinting label ${labelId}`, {
      description: "Watermark 'RePrint' applied.",
    });
  };

  return (
    <div className="h-full flex flex-col">
      {/* Toolbar + Filters - style consistent with Labels / Location Manager */}
      <div className="pb-4">
        {/* Row 1: Partner, Group, Location dropdowns + Period Search, Product search, Export */}
        <div className="flex flex-wrap items-center gap-3">
          <Select defaultValue="partner-a">
            <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
              <SelectValue placeholder="Partner" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="partner-a">Partner A</SelectItem>
            </SelectContent>
          </Select>
          <Select defaultValue="group-b">
            <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
              <SelectValue placeholder="Group" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="group-b">Group B</SelectItem>
            </SelectContent>
          </Select>
          <Select defaultValue="loc-12345">
            <SelectTrigger className="w-[160px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0" style={{ height: 40, boxSizing: 'border-box' }}>
              <SelectValue placeholder="Location" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="loc-12345">Downtown Store</SelectItem>
              <SelectItem value="all">All Locations</SelectItem>
            </SelectContent>
          </Select>
          <div className="flex items-center gap-2 shrink-0">
            <span className="text-sm font-medium text-gray-700">Period Search:</span>
            <div className="flex items-center bg-white border border-gray-300 rounded-md h-10 px-2" style={{ minHeight: 40 }}>
              <Calendar className="w-4 h-4 text-gray-500 mr-2 shrink-0" />
              <input type="date" className="text-sm outline-none w-32 bg-transparent" />
              <span className="mx-2 text-gray-400">-</span>
              <input type="date" className="text-sm outline-none w-32 bg-transparent" />
            </div>
          </div>
          <div className="flex items-center w-64 rounded-md border border-gray-300 bg-white overflow-hidden shrink-0" style={{ height: 40 }}>
              <Search className="h-4 w-4 text-gray-400 shrink-0 ml-3 pointer-events-none" />
              <Input
                placeholder="Search Product or Category..."
                className="flex-1 min-w-0 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 py-2 px-2 h-full placeholder:text-gray-500"
              />
          </div>
          <div className="flex-1 min-w-2" />
          <Button variant="outline" className="h-10 border border-gray-300 rounded-md text-gray-900 bg-white hover:bg-gray-50 gap-2 shrink-0">
            <Download className="w-4 h-4" /> Export Report
          </Button>
        </div>

        {/* Tabs - underline spans full width */}
        <div className="w-full border-b border-gray-200 mt-4">
          <div className="flex overflow-x-auto w-fit">
            <button
              onClick={() => setActiveTab('print-log')}
              style={activeTab === 'print-log' ? { borderBottomWidth: 2, borderBottomStyle: 'solid', borderBottomColor: '#2563eb' } : undefined}
              className={cn(
                "px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
                activeTab === 'print-log' ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
              )}
            >
              Print Log
            </button>
            <button
              onClick={() => setActiveTab('label-report')}
              style={activeTab === 'label-report' ? { borderBottomWidth: 2, borderBottomStyle: 'solid', borderBottomColor: '#2563eb' } : undefined}
              className={cn(
                "px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
                activeTab === 'label-report' ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
              )}
            >
              Label Report
            </button>
          </div>
        </div>
      </div>

      {/* Content Area - same padding as Labels */}
      <div className="flex-1 overflow-auto pt-6">
        {activeTab === 'print-log' && (
          <div className="bg-white border border-gray-200 shadow-sm rounded-md overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-100 hover:bg-gray-100">
                  <TableHead className="text-gray-900 font-bold border-r">Label ID</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Product Name</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Category</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Template</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Printed At</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Printed By</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Location</TableHead>
                  <TableHead className="text-gray-900 font-bold border-r">Expiry Date</TableHead>
                  <TableHead className="text-gray-900 font-bold text-center">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {MOCK_PRINT_LOG.map((log) => (
                  <TableRow key={log.id}>
                    <TableCell className="border-r font-numeric text-gray-600">{log.id}</TableCell>
                    <TableCell className="border-r font-medium">{log.productName}</TableCell>
                    <TableCell className="border-r">
                      <Badge variant="secondary" className="bg-blue-50 text-blue-700 hover:bg-blue-50 border-blue-200">
                        {log.category}
                      </Badge>
                    </TableCell>
                    <TableCell className="border-r text-gray-600 text-sm">
                      {(() => {
                        const hasAlert = log.template.endsWith(' !!!');
                        const main = hasAlert ? log.template.slice(0, -4) : log.template;
                        const lastSpace = main.lastIndexOf(' ');
                        const prefix = main.slice(0, lastSpace + 1);
                        const boldPart = main.slice(lastSpace + 1);
                        return (
                          <>
                            {prefix}
                            <span className="font-bold text-gray-900">{boldPart}</span>
                            {hasAlert && <span className="text-red-600"> !!!</span>}
                          </>
                        );
                      })()}
                    </TableCell>
                    <TableCell className="border-r text-gray-600 text-sm font-numeric">{log.printedAt}</TableCell>
                    <TableCell className="border-r text-gray-600 text-sm">{log.printedBy}</TableCell>
                    <TableCell className="border-r text-gray-600 text-sm font-numeric">{log.location}</TableCell>
                    <TableCell className="border-r">
                       <span className={cn(
                         "text-sm font-medium font-numeric",
                         log.status === 'Expired' ? 'text-red-600' : 
                         log.status === 'Expiring Soon' ? 'text-orange-500' : 'text-green-600'
                       )}>
                         {log.expiryDate}
                       </span>
                    </TableCell>
                    <TableCell className="text-center">
                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="h-8 gap-1 hover:bg-gray-100 border-gray-300"
                        onClick={() => handleReprint(log.id)}
                      >
                        <Printer className="w-3 h-3" /> Reprint
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        )}

        {activeTab === 'label-report' && (
          <div className="space-y-6">
            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Total Labels Printed</CardTitle>
                  <FileText className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">2,543</div>
                  <p className="text-xs text-muted-foreground">+20.1% from last month</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Most Printed Category</CardTitle>
                  <BarChart3 className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">Dairy</div>
                  <p className="text-xs text-muted-foreground">450 labels generated</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Top Product</CardTitle>
                  <ArrowUpRight className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">Whole Milk</div>
                  <p className="text-xs text-muted-foreground">182 labels generated</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Avg. Daily Prints</CardTitle>
                  <RefreshCw className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">85</div>
                  <p className="text-xs text-muted-foreground">+12% from last week</p>
                </CardContent>
              </Card>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Category Breakdown Chart */}
              <Card className="col-span-1">
                <CardHeader>
                  <CardTitle>Labels by Category</CardTitle>
                  <CardDescription>
                    Distribution of printed labels across product categories.
                  </CardDescription>
                </CardHeader>
                <CardContent className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={MOCK_CATEGORY_STATS}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} />
                      <XAxis dataKey="name" fontSize={12} tickLine={false} axisLine={false} />
                      <YAxis fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `${value}`} />
                      <Tooltip />
                      <Bar dataKey="count" fill="#facc15" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                </CardContent>
              </Card>

              {/* Usage Trend Chart */}
              <Card className="col-span-1">
                 <CardHeader>
                  <CardTitle>Print Volume Trends</CardTitle>
                  <CardDescription>
                    Daily label printing volume for the last 7 days.
                  </CardDescription>
                </CardHeader>
                <CardContent className="h-[300px]">
                  <ResponsiveContainer width="100%" height="100%">
                    <RechartsLineChart data={MOCK_USAGE_TRENDS}>
                      <CartesianGrid strokeDasharray="3 3" vertical={false} />
                      <XAxis dataKey="date" fontSize={12} tickLine={false} axisLine={false} />
                      <YAxis fontSize={12} tickLine={false} axisLine={false} />
                      <Tooltip />
                      <Line type="monotone" dataKey="count" stroke="#dc2626" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
                    </RechartsLineChart>
                  </ResponsiveContainer>
                </CardContent>
              </Card>
            </div>
            
            {/* Top Products Table */}
            <Card>
              <CardHeader>
                <CardTitle>Most Used Products</CardTitle>
              </CardHeader>
              <CardContent>
                 <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Product Name</TableHead>
                      <TableHead>Category</TableHead>
                      <TableHead className="text-right">Total Printed</TableHead>
                      <TableHead className="text-right">Usage %</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    <TableRow>
                      <TableCell className="font-medium">Whole Milk</TableCell>
                      <TableCell>Dairy</TableCell>
                      <TableCell className="text-right">182</TableCell>
                      <TableCell className="text-right">7.2%</TableCell>
                    </TableRow>
                     <TableRow>
                      <TableCell className="font-medium">Ground Beef 80/20</TableCell>
                      <TableCell>Meat</TableCell>
                      <TableCell className="text-right">145</TableCell>
                      <TableCell className="text-right">5.7%</TableCell>
                    </TableRow>
                     <TableRow>
                      <TableCell className="font-medium">Chicken Breast</TableCell>
                      <TableCell>Meat</TableCell>
                      <TableCell className="text-right">132</TableCell>
                      <TableCell className="text-right">5.2%</TableCell>
                    </TableRow>
                     <TableRow>
                      <TableCell className="font-medium">Sliced Ham</TableCell>
                      <TableCell>Deli</TableCell>
                      <TableCell className="text-right">98</TableCell>
                      <TableCell className="text-right">3.8%</TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </CardContent>
            </Card>

          </div>
        )}
      </div>
    </div>
  );
}
