import { ArrowLeft } from 'lucide-react';

import { Head, Link, useForm } from '@inertiajs/react';

import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { ConfirmDialog } from '@/Components/ui/confirm-dialog';
import { EmptyState } from '@/Components/ui/empty-state';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { SUBSCRIPTION_STATUS_VARIANT } from '@/config/billing-constants';
import AdminLayout from '@/Layouts/AdminLayout';
import { capitalize, formatDate } from '@/lib/format';
import type { AdminBillingShowProps } from '@/types/admin';

function CancelSubscriptionForm({ subscriptionId }: { subscriptionId: number }) {
  const { data, setData, post, processing } = useForm({ immediately: false });

  const handleCancel = () => {
    post(`/admin/billing/subscriptions/${subscriptionId}/cancel`);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          id="cancel-immediately"
          checked={data.immediately}
          onChange={(e) => setData('immediately', e.target.checked)}
          className="h-4 w-4 rounded border-border"
        />
        <Label htmlFor="cancel-immediately" className="text-sm font-normal">
          Cancel immediately (otherwise at period end)
        </Label>
      </div>
      <ConfirmDialog
        trigger={
          <Button variant="destructive" size="sm" disabled={processing}>
            Cancel Subscription
          </Button>
        }
        title="Cancel Subscription"
        description={
          data.immediately
            ? 'This will immediately cancel the subscription. The user will lose access right away.'
            : "This will cancel the subscription at the end of the current billing period. The user retains access until then."
        }
        variant="destructive"
        confirmLabel="Yes, Cancel"
        onConfirm={handleCancel}
      />
    </div>
  );
}

function ExtendTrialForm({ subscriptionId }: { subscriptionId: number }) {
  const { data, setData, post, processing } = useForm({ days: '7' });

  const handleExtend = () => {
    post(`/admin/billing/subscriptions/${subscriptionId}/extend-trial`);
  };

  return (
    <div className="space-y-3">
      <div className="space-y-1.5">
        <Label htmlFor="extend-days">Days to extend</Label>
        <Input
          id="extend-days"
          type="number"
          min={1}
          max={90}
          value={data.days}
          onChange={(e) => setData('days', e.target.value)}
          className="w-32"
        />
      </div>
      <ConfirmDialog
        trigger={
          <Button variant="outline" size="sm" disabled={processing || !data.days || Number(data.days) < 1}>
            Extend Trial
          </Button>
        }
        title="Extend Trial Period"
        description={`This will extend the trial period by ${data.days} day(s) from today. A new Stripe trial end date will be set.`}
        confirmLabel="Extend Trial"
        onConfirm={handleExtend}
      />
    </div>
  );
}

function AssignPlanForm({
  subscriptionId,
  availablePlans,
}: {
  subscriptionId: number;
  availablePlans: AdminBillingShowProps['available_plans'];
}) {
  const { data, setData, post, processing } = useForm({ price_id: '' });

  const handleAssign = () => {
    post(`/admin/billing/subscriptions/${subscriptionId}/assign-plan`);
  };

  if (availablePlans.length === 0) {
    return <p className="text-sm text-muted-foreground">No plans configured (STRIPE_PRICE_* env vars required).</p>;
  }

  return (
    <div className="space-y-3">
      <div className="space-y-1.5">
        <Label htmlFor="assign-plan">Target plan</Label>
        <Select value={data.price_id} onValueChange={(v) => setData('price_id', v)}>
          <SelectTrigger id="assign-plan" className="w-64">
            <SelectValue placeholder="Select a plan..." />
          </SelectTrigger>
          <SelectContent>
            {availablePlans.map((plan) => (
              <SelectItem key={plan.value} value={plan.value}>
                {plan.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <ConfirmDialog
        trigger={
          <Button variant="outline" size="sm" disabled={processing || !data.price_id}>
            Assign Plan
          </Button>
        }
        title="Assign Plan"
        description="This will immediately swap the subscription to the selected Stripe price. Proration will be applied per the subscription's proration behaviour."
        confirmLabel="Assign Plan"
        onConfirm={handleAssign}
      />
    </div>
  );
}

export default function BillingShow({ subscription, items, audit_logs, available_plans }: AdminBillingShowProps) {
  return (
    <AdminLayout>
      <Head title={`Admin - Subscription #${subscription.id}`} />

      <div className="container py-6 space-y-6">
        {/* Breadcrumb */}
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin/billing">Billing</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin/billing/subscriptions">Subscriptions</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>#{subscription.id}</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <PageHeader
          title={`Subscription #${subscription.id}`}
          description={`${subscription.user_name} (${subscription.user_email})`}
        />

        <div className="grid gap-6 md:grid-cols-2">
          {/* Subscription Info */}
          <Card>
            <CardHeader>
              <CardTitle>Subscription Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Status</span>
                <Badge
                  variant={SUBSCRIPTION_STATUS_VARIANT[subscription.stripe_status] ?? 'secondary'}
                >
                  {subscription.stripe_status}
                </Badge>
              </div>
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Tier</span>
                <Badge variant="outline">{capitalize(subscription.tier)}</Badge>
              </div>
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Quantity</span>
                <span className="text-sm">{subscription.quantity}</span>
              </div>
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Stripe ID</span>
                <span className="text-sm font-mono max-w-50 truncate inline-block">
                  {subscription.stripe_id}
                </span>
              </div>
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Created</span>
                <span className="text-sm">{formatDate(subscription.created_at)}</span>
              </div>
              {subscription.trial_ends_at && (
                <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                  <span className="text-sm text-muted-foreground">Trial Ends</span>
                  <span className="text-sm">{formatDate(subscription.trial_ends_at)}</span>
                </div>
              )}
              {subscription.ends_at && (
                <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                  <span className="text-sm text-muted-foreground">Ends At</span>
                  <span className="text-sm">{formatDate(subscription.ends_at)}</span>
                </div>
              )}
            </CardContent>
          </Card>

          {/* User Card */}
          <Card>
            <CardHeader>
              <CardTitle>Subscriber</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Name</span>
                <span className="text-sm">{subscription.user_name}</span>
              </div>
              <div className="flex flex-col sm:flex-row sm:justify-between gap-1">
                <span className="text-sm text-muted-foreground">Email</span>
                <span className="text-sm">{subscription.user_email}</span>
              </div>
              <Button variant="outline" size="sm" asChild className="mt-2">
                <Link href={`/admin/users/${subscription.user_id}`}>View User Profile</Link>
              </Button>
            </CardContent>
          </Card>
        </div>

        {/* Subscription Items */}
        <Card>
          <CardHeader>
            <CardTitle>Subscription Items</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Product</TableHead>
                    <TableHead>Price</TableHead>
                    <TableHead>Tier</TableHead>
                    <TableHead>Quantity</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {items.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-sm font-mono max-w-50 truncate">
                        {item.stripe_product}
                      </TableCell>
                      <TableCell className="text-sm font-mono max-w-50 truncate">
                        {item.stripe_price}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{capitalize(item.tier)}</Badge>
                      </TableCell>
                      <TableCell className="text-sm">{item.quantity}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* Billing Audit Logs */}
        <Card>
          <CardHeader>
            <CardTitle>Billing Activity</CardTitle>
          </CardHeader>
          <CardContent>
            {audit_logs.length === 0 ? (
              <EmptyState
                title="No billing events"
                description="Billing-related audit logs for this user will appear here."
                size="sm"
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Event</TableHead>
                      <TableHead>Date</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {audit_logs.map((log) => (
                      <TableRow key={log.id}>
                        <TableCell>
                          <Link
                            href={`/admin/audit-logs/${log.id}`}
                            className="hover:opacity-80 transition-opacity"
                          >
                            <Badge variant="secondary">{log.event}</Badge>
                          </Link>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatDate(log.created_at)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Admin Actions */}
        <Card>
          <CardHeader>
            <CardTitle>Admin Actions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <h4 className="text-sm font-medium">Cancel Subscription</h4>
              <p className="text-sm text-muted-foreground">
                Cancel at period end or immediately. Requires password confirmation.
              </p>
              <CancelSubscriptionForm subscriptionId={subscription.id} />
            </div>

            <div className="border-t border-border pt-4 space-y-2">
              <h4 className="text-sm font-medium">Extend Trial</h4>
              <p className="text-sm text-muted-foreground">
                Push the trial end date forward by the specified number of days.
              </p>
              <ExtendTrialForm subscriptionId={subscription.id} />
            </div>

            <div className="border-t border-border pt-4 space-y-2">
              <h4 className="text-sm font-medium">Assign Plan</h4>
              <p className="text-sm text-muted-foreground">
                Swap the subscription to a different Stripe price. Immediate effect with proration.
              </p>
              <AssignPlanForm subscriptionId={subscription.id} availablePlans={available_plans} />
            </div>
          </CardContent>
        </Card>

        <Button variant="outline" asChild>
          <Link href="/admin/billing/subscriptions">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Subscriptions
          </Link>
        </Button>
      </div>
    </AdminLayout>
  );
}
