'use client';

import * as React from 'react';
import { motion } from 'motion/react';

// Import recharts components
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Cell
} from 'recharts';

import { cn } from '@workspace/ui/lib/utils';
import { Button } from '@workspace/ui/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@workspace/ui/components/ui/card';
import { Input } from '@workspace/ui/components/ui/input';
import { Label } from '@workspace/ui/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@workspace/ui/components/ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@workspace/ui/components/ui/dialog';

// Import html2pdf
import html2pdf from 'html2pdf.js';

// Mock data for calculator inputs
const WORKLOAD_OPTIONS = [
  { value: 'web', label: 'Web Application' },
  { value: 'media', label: 'Media Streaming' },
  { value: 'ml', label: 'Machine Learning' },
  { value: 'db', label: 'Database' },
];

const AVAILABILITY_OPTIONS = [
  { value: 'single', label: 'Single Region' },
  { value: 'multi', label: 'Multi-Region' },
];

// Mock calculation function (replace with actual logic)
const calculateTCO = (inputs: any) => {
  // Placeholder logic
  const capex = 50000;
  const monthlyOpex = 2000;
  const breakEvenMonths = 24;
  const year1TCO = capex + (monthlyOpex * 12);
  const year3TCO = capex + (monthlyOpex * 36);
  const perfParity = true;

  // Data for the chart
  const chartData = [
    { name: 'Year 1', capex, opex: monthlyOpex * 12 },
    { name: 'Year 2', capex: 0, opex: monthlyOpex * 12 },
    { name: 'Year 3', capex: 0, opex: monthlyOpex * 12 },
  ];

  return {
    capex,
    monthlyOpex,
    breakEvenMonths,
    year1TCO,
    year3TCO,
    perfParity,
    chartData,
  };
};

export interface CostCalculatorProps extends React.HTMLAttributes<HTMLDivElement> {
  // Props for initial values if needed
}

export function CostCalculator({ className, ...props }: CostCalculatorProps) {
  const [users, setUsers] = React.useState('100');
  const [storageTB, setStorageTB] = React.useState('10');
  const [egressTB, setEgressTB] = React.useState('1');
  const [workload, setWorkload] = React.useState('web');
  const [availability, setAvailability] = React.useState('single');
  const [currentCloudCost, setCurrentCloudCost] = React.useState('10000');
  
  const [results, setResults] = React.useState<ReturnType<typeof calculateTCO> | null>(null);
  const [isCalculating, setIsCalculating] = React.useState(false);
  const resultsRef = React.useRef<HTMLDivElement>(null);

  const handleCalculate = () => {
    setIsCalculating(true);
    // Simulate calculation delay
    setTimeout(() => {
      const calculatedResults = calculateTCO({
        users: Number(users),
        storageTB: Number(storageTB),
        egressTB: Number(egressTB),
        workload,
        availability,
        currentCloudCost: Number(currentCloudCost),
      });
      setResults(calculatedResults);
      setIsCalculating(false);
    }, 500);
  };

  const exportPDF = () => {
    if (resultsRef.current) {
      const element = resultsRef.current;
      const options = {
        margin: 10,
        filename: 'fortura-cost-estimate.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
      };

      html2pdf().set(options).from(element).save();
    }
  };

  // Trigger initial calculation
  React.useEffect(() => {
    handleCalculate();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Colors for the chart bars
  const COLORS = ['#8884d8', '#82ca9d'];

  return (
    <div className={cn("w-full max-w-4xl mx-auto", className)} {...props}>
      <Card>
        <CardHeader>
          <CardTitle>Cloud Cost Calculator</CardTitle>
          <CardDescription>Estimate your Total Cost of Ownership (TCO) with Fortura.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-4">
              <div>
                <Label htmlFor="users">Number of Users</Label>
                <Input
                  id="users"
                  type="number"
                  value={users}
                  onChange={(e) => setUsers(e.target.value)}
                  min="1"
                />
              </div>
              <div>
                <Label htmlFor="storage">Storage (TB)</Label>
                <Input
                  id="storage"
                  type="number"
                  value={storageTB}
                  onChange={(e) => setStorageTB(e.target.value)}
                  min="1"
                  step="10"
                />
              </div>
              <div>
                <Label htmlFor="egress">Monthly Egress (TB)</Label>
                <Input
                  id="egress"
                  type="number"
                  value={egressTB}
                  onChange={(e) => setEgressTB(e.target.value)}
                  min="0"
                  step="10"
                />
              </div>
            </div>
            <div className="space-y-4">
              <div>
                <Label htmlFor="workload">Workload Class</Label>
                <Select value={workload} onValueChange={setWorkload}>
                  <SelectTrigger id="workload">
                    <SelectValue placeholder="Select workload" />
                  </SelectTrigger>
                  <SelectContent>
                    {WORKLOAD_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="availability">Availability Tier</Label>
                <Select value={availability} onValueChange={setAvailability}>
                  <SelectTrigger id="availability">
                    <SelectValue placeholder="Select availability" />
                  </SelectTrigger>
                  <SelectContent>
                    {AVAILABILITY_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>
                        {option.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="current-cost">Current Monthly Cloud Cost ($)</Label>
                <Input
                  id="current-cost"
                  type="number"
                  value={currentCloudCost}
                  onChange={(e) => setCurrentCloudCost(e.target.value)}
                  min="0"
                />
              </div>
            </div>
          </div>
          <div className="mt-6 flex justify-center">
            <Button onClick={handleCalculate} disabled={isCalculating}>
              {isCalculating ? 'Calculating...' : 'Recalculate'}
            </Button>
          </div>
        </CardContent>
        {results && (
          <CardContent ref={resultsRef} className="border-t pt-6">
            <h3 className="text-lg font-semibold mb-4">Estimated TCO</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">Year 1 TCO</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">${results.year1TCO.toLocaleString()}</div>
                  <p className="text-xs text-muted-foreground">Capex: ${results.capex.toLocaleString()}</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">Year 3 TCO</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">${results.year3TCO.toLocaleString()}</div>
                  <p className="text-xs text-muted-foreground">Monthly Opex: ${results.monthlyOpex.toLocaleString()}</p>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">Break-even</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{results.breakEvenMonths} months</div>
                  <p className="text-xs text-muted-foreground">
                    {results.perfParity ? "Performance parity" : "Performance may vary"}
                  </p>
                </CardContent>
              </Card>
            </div>
            
            {/* Chart */}
            <div className="h-64 mb-6">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={results.chartData}
                  margin={{
                    top: 20,
                    right: 30,
                    left: 20,
                    bottom: 5,
                  }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip formatter={(value) => [`${Number(value).toLocaleString()}`, '']} />
                  <Legend />
                  <Bar dataKey="capex" name="Capex" fill={COLORS[0]} >
                    {results.chartData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[0]} />
                    ))}
                  </Bar>
                  <Bar dataKey="opex" name="Opex" fill={COLORS[1]} >
                    {results.chartData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[1]} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
            
            <div className="flex justify-center space-x-4">
              <Dialog>
                <DialogTrigger asChild>
                  <Button variant="outline">Email Estimate</Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-md">
                  <DialogHeader>
                    <DialogTitle>Email Estimate</DialogTitle>
                    <DialogDescription>
                      Enter your email address and we'll send you a copy of this estimate.
                    </DialogDescription>
                  </DialogHeader>
                  <div className="flex items-center space-x-2">
                    <div className="grid flex-1 gap-2">
                      <Label htmlFor="email" className="sr-only">
                        Email
                      </Label>
                      <Input
                        id="email"
                        type="email"
                        placeholder="Enter your email"
                      />
                    </div>
                    <Button type="submit" size="sm" className="px-3">
                      Send
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
              <Button variant="outline" onClick={exportPDF}>Export PDF</Button>
            </div>
          </CardContent>
        )}
      </Card>
    </div>
  );
}