
'use client';

import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  MapPin,
  Calendar,
  DollarSign,
  FileText,
  CheckCircle,
  XCircle,
  AlertCircle,
} from 'lucide-react';

type QuoteDetailsDialogProps = {
  quote: {
    id: string;
    quoteNumber: string;
    services: string[];
    total: number;
    status: string;
    isAccepted: boolean;
    validUntil: string;
    createdAt: string;
    sentAt: string | null;
    propertyData: {
      address?: string;
      coordinates?: { lat: number; lng: number };
      measurements?: any;
    };
    lineItems: Array<{
      description: string;
      quantity: number;
      unit: string;
      unitPrice: number;
      total: number;
    }>;
    subtotal: number;
    discounts: number;
    taxes: number;
    notes?: string;
    termsConditions?: string;
  };
  open: boolean;
  onClose: () => void;
  onAccept: (quoteId: string) => void;
  onReject: (quoteId: string, reason: string) => void;
};

export function QuoteDetailsDialog({
  quote,
  open,
  onClose,
  onAccept,
  onReject,
}: QuoteDetailsDialogProps) {
  const [showRejectDialog, setShowRejectDialog] = useState(false);
  const [rejectionReason, setRejectionReason] = useState('');

  const isExpired = new Date(quote.validUntil) < new Date();
  const canAccept = (quote.status === 'SENT' || quote.status === 'VIEWED') && !quote.isAccepted && !isExpired;

  const handleAccept = () => {
    onAccept(quote.id);
    onClose();
  };

  const handleReject = () => {
    if (!rejectionReason.trim()) {
      return;
    }
    onReject(quote.id, rejectionReason);
    setShowRejectDialog(false);
    setRejectionReason('');
    onClose();
  };

  return (
    <>
      <Dialog open={open && !showRejectDialog} onOpenChange={(open) => !open && onClose()}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-2xl">{quote.quoteNumber}</DialogTitle>
            <DialogDescription>
              Quote details and pricing breakdown
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-6">
            {/* Status and Info */}
            <div className="flex flex-wrap gap-4">
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  Created: {new Date(quote.createdAt).toLocaleDateString()}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span className="text-sm">
                  Valid until: {new Date(quote.validUntil).toLocaleDateString()}
                </span>
              </div>
              {isExpired && (
                <Badge variant="destructive" className="flex items-center gap-1">
                  <AlertCircle className="h-3 w-3" />
                  Expired
                </Badge>
              )}
            </div>

            {/* Property Information */}
            {quote.propertyData?.address && (
              <div className="space-y-2">
                <h4 className="font-semibold flex items-center gap-2">
                  <MapPin className="h-4 w-4" />
                  Property Address
                </h4>
                <p className="text-sm text-muted-foreground">{quote.propertyData.address}</p>
              </div>
            )}

            {/* Services */}
            <div className="space-y-2">
              <h4 className="font-semibold flex items-center gap-2">
                <FileText className="h-4 w-4" />
                Services
              </h4>
              <div className="flex flex-wrap gap-2">
                {quote.services.map((service, index) => (
                  <Badge key={index} variant="secondary">
                    {service}
                  </Badge>
                ))}
              </div>
            </div>

            {/* Measurements */}
            {quote.propertyData?.measurements && (
              <div className="space-y-2">
                <h4 className="font-semibold">Measurements</h4>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2 text-sm">
                  {Object.entries(quote.propertyData.measurements).map(([key, value]) => (
                    <div key={key} className="bg-muted p-2 rounded">
                      <span className="font-medium capitalize">{key.replace(/([A-Z])/g, ' $1')}: </span>
                      <span>{String(value)}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <Separator />

            {/* Line Items */}
            <div className="space-y-2">
              <h4 className="font-semibold">Pricing Breakdown</h4>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Description</TableHead>
                    <TableHead className="text-right">Quantity</TableHead>
                    <TableHead className="text-right">Unit Price</TableHead>
                    <TableHead className="text-right">Total</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {quote.lineItems.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell className="font-medium">{item.description}</TableCell>
                      <TableCell className="text-right">
                        {item.quantity} {item.unit}
                      </TableCell>
                      <TableCell className="text-right">${item.unitPrice.toLocaleString()}</TableCell>
                      <TableCell className="text-right">${item.total.toLocaleString()}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            {/* Totals */}
            <div className="space-y-2 bg-muted p-4 rounded-lg">
              <div className="flex justify-between text-sm">
                <span>Subtotal:</span>
                <span>${quote.subtotal.toLocaleString()}</span>
              </div>
              {quote.discounts > 0 && (
                <div className="flex justify-between text-sm text-green-600">
                  <span>Discounts:</span>
                  <span>-${quote.discounts.toLocaleString()}</span>
                </div>
              )}
              <div className="flex justify-between text-sm">
                <span>Taxes:</span>
                <span>${quote.taxes.toLocaleString()}</span>
              </div>
              <Separator />
              <div className="flex justify-between text-lg font-bold">
                <span>Total:</span>
                <span>${quote.total.toLocaleString()}</span>
              </div>
            </div>

            {/* Notes */}
            {quote.notes && (
              <div className="space-y-2">
                <h4 className="font-semibold">Notes</h4>
                <p className="text-sm text-muted-foreground">{quote.notes}</p>
              </div>
            )}

            {/* Terms and Conditions */}
            {quote.termsConditions && (
              <div className="space-y-2">
                <h4 className="font-semibold">Terms & Conditions</h4>
                <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                  {quote.termsConditions}
                </p>
              </div>
            )}
          </div>

          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={onClose}>
              Close
            </Button>
            {canAccept && (
              <>
                <Button
                  variant="destructive"
                  onClick={() => setShowRejectDialog(true)}
                >
                  <XCircle className="h-4 w-4 mr-2" />
                  Reject
                </Button>
                <Button onClick={handleAccept}>
                  <CheckCircle className="h-4 w-4 mr-2" />
                  Accept Quote
                </Button>
              </>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Rejection Dialog */}
      <Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject Quote</DialogTitle>
            <DialogDescription>
              Please provide a reason for rejecting this quote. This will help us serve you better.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="reason">Reason for Rejection</Label>
              <Textarea
                id="reason"
                placeholder="e.g., Price too high, Need different services, Timeline doesn't work..."
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRejectDialog(false)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleReject}
              disabled={!rejectionReason.trim()}
            >
              Reject Quote
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
